Can't define static abstract string property

Static members do not have polymorphism, so they can't be abstract. :(

If that's what you need, consider making a Singleton object, and reading the property off that object.


Just use new to override a static method in a derived class. Nothing that makes new a bad thing to do for virtual methods and properties applies since the type name must be supplied:

public class BaseClass
{
    public static int Max { get { return 0; } }
}

public class InteriorClass : BaseClass
{
}

public class DerivedClass : InteriorClass
{
    public new static int Max { get { return BaseClass.Max + 1; } }
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("BaseClass.Max = {0}", BaseClass.Max);
        Console.WriteLine("InteriorClass.Max = {0}", InteriorClass.Max);
        Console.WriteLine("DerivedClass.Max = {0}", DerivedClass.Max);
        Console.ReadKey();
    }
}

Ok, this is not exactly to create an static abstract property, but you can achieve the desired effect.

You can get this by using generics:

public abstract class MyAbstractClass<T>
{
    public static string MyAbstractString{ get; set; }
    public static string GetMyAbstracString()
    {

        return "Who are you? " + MyAbstractString;

    }
}

public class MyDerivedClass : MyAbstractClass<MyDerivedClass>
{
    public static new string MyAbstractString
    { 
        get 
        { 
            return MyAbstractClass<MyDerivedClass>.MyAbstractString; 
        }
        set
        {
            MyAbstractClass<MyDerivedClass>.MyAbstractString = value;            
        }
    }

}


public class MyDerivedClassTwo : MyAbstractClass<MyDerivedClassTwo>
{
    public static new string MyAbstractString
    {
        get
        {
            return MyAbstractClass<MyDerivedClassTwo>.MyAbstractString;
        }
        set
        {
            MyAbstractClass<MyDerivedClassTwo>.MyAbstractString = value;
        }
    }

}


public class Test
{

    public void Test()
    {

        MyDerivedClass.MyAbstractString = "I am MyDerivedClass";
        MyDerivedClassTwo.MyAbstractString = "I am MyDerivedClassTwo";


        Debug.Print(MyDerivedClass.GetMyAbstracString());
        Debug.Print(MyDerivedClassTwo.GetMyAbstracString());


    }

}

So, calling the test class you will get:

"Who are you? I am MyDerivedClass" "Who are you? I am MyDerivedClassTwo"

So, you have an static method in an abstract class but the abstract value is different for each derived class, nice :D

Ok, so, what's going here? The trick is the generic tag, the compiler is generating a different abstract class for each derived type.

As I said it's not an abstract property, but you get all benefits of abstract static properties, which are programming static functions on your abstract class but using different static parameters per type.

Tags:

C#

.Net