fravelgue
fravelgue

Reputation: 2873

Statics Properties in abstract classes

Could anybody explain why the static property is null?

class Program
{
    static void Main(string[] args)
    {
        string s = Cc.P1; // is null
    }
}

public class Cc
    : Ca
{
    static Cc()
    {
        P1 = "Test";
    }
}

public abstract class Ca
{
    public static string P1
    {
        get;
        protected set;
    }
}

Upvotes: 2

Views: 1595

Answers (4)

Sergey Teplyakov
Sergey Teplyakov

Reputation: 11657

You misuse some OOD principles in your code. For example, you mix in your classes static behavior (witch is something like Singleton design pattern) and polymorphism (you use abstract base class but without any base class interface). And because we have no such thing like "Static Polymorphism" we should separate this two roles.

If you describe in more details what problem are you trying to solve, maybe you receive more accurate answers.

But anyway you may implement something like this:

public class Cc : Ca
{
    private Cc()
        : base("Test")
    {
       //We may call protected setter here
    }

    private static Ca instance = new Cc();
    public static Ca Instance
    {
        get { return instance; }
    }
}

public abstract class Ca
{
    protected Ca(string p1)
    {
        P1 = p1;
    }

    //You may use protected setter and call this setter in descendant constructor
    public string P1
    {
        get;
        private set;
    }
}


static void Main(string[] args)
{
    string s = Cc.Instance.P1; // is not null
}

Upvotes: 0

Cheng Chen
Cheng Chen

Reputation: 43523

If you really want the value:

new Cc();  // call the static constructor
string s = Cc.P1; // not null now

Upvotes: 0

Paul Hadfield
Paul Hadfield

Reputation: 6136

Try the following:

string s = Cc.P1; // is null
Cc c = new Cc();
s = Cc.P1; // is it still null

If P1 is no longer null, it is because accessing the static P1 (in Ca) does not cause the static instance of Cc to fire (and therefore assign the value in the static constructor).

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292465

That because when you write Cc.P1, you're actually referring to Ca.P1 because that's where it is declared (since P1 is static, it is not involved in polymorphism). So in spite of appearances, your code isn't using the Cc class at all, and the Cc static constructor is not executed.

Upvotes: 6

Related Questions