Click here to Skip to main content
15,885,141 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
public abstract class A
    {
        public static string f { get; set; }
    }

    public class B : A {
        static B()
        {
            f = "B";
        }
    }

    public class C : A
    {
        static C()
        {
            f = "C";
        }
    }


What I have tried:

C c = new C();
B b = new B();
The result is:
C.f is B
B.f is B
A.f is B

what i expect is:
C.f is C
B.f is B
A.f is NULL

How to implement this using static property?
Posted
Updated 21-Sep-18 21:32pm

f is static: there is one of it for the whole application. Because both B and C are derived from A, they share the same static variable: the last value to you set it to will be the global value it has, regardless of whether you set it via an instance of B or C

So which ever instance you create most recently defines the value of f .
 
Share this answer
 
v2
i found a solution of this:
C#
public abstract class A
{
    public static string f { get; set; }
}


public class B : A 
{
    public new static string f { get; set; }

    static B()
    {
        f = "B";
    }
}

public class C : A
{
    public new static string f { get; set; } 

    static C()
    {
        f = "C";
    }
}
 
Share this answer
 
v2
A static member is the same for every instance of the class and its derived children.
The solution you found completely defeats the point of having a static property.
Why do you think you need the property to be static, if it can be different for every child class?

Edit: example implementation.
C#
public abstract class A
{
   public string F { get; protected set; }
}

public class B : A
{
   public B()
   {
      F = "B Class";
   }
}

public class C : A
{
   public C()
   {
      F = "C Class";
   }
}

Hope this helps.
 
Share this answer
 
v2
Comments
855 22-Sep-18 14:13pm    
Say i have a Product class which has a ProductType field. And two child class, mouse and keyboard which ProductType is mouse or keyboard. So the ProductType can be used in the scope of each child class.
phil.o 22-Sep-18 22:49pm    
But that does not mean that the ProductType property has to be static :)
855 23-Sep-18 11:32am    
my goal is to share the ProductType in each child class.
In this scenario, do you have other suggestions? thanks.
phil.o 24-Sep-18 17:45pm    
Just leave the property as non static in the base class. In child classes' constructors, just assign the desired value.
You can make the property's accessor public for the get and protected for the set; this way, it will be publicly readable on instances of the classes, but only writeable from the child classes implementations.
I updated my solution to give you a quick example.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900