Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to initial static property is derived from base class as below code.

C#
class A
      {
            protected static string keyName { get; set; }

            static A()
            {
                  Initial();
            }
            public static void Initial()
            {
               
                 string a = keyName;
                
            }
      }

class B:A
      {
         
            static B()
            {
                  keyName = "NewId";
            }

        
      }


What I have tried:

I want to get value of variable keyName in Initial function.
Posted
Updated 25-Jan-18 23:00pm
Comments
Ralf Meier 26-Jan-18 3:43am    
I'm not sure what you try to achieve.
Normally a Property has a Getter and a Setter and a Variable which holds the assigned content.
I don't find any of that in your code snippet.
I suggest you to read first how to use and code properties generally. After that you could improve your question ... and perhaps you could be helped ...
But also you could describe your goal and how you want to achieve it ...

1 solution

The problem is that you can't do that: the static constructor for B is not called until an instance of B is first used.
So if an instance of A is constructed:
C#
A a = new A();
Then the value of the keyName property is never initialized (and thus null).
One way to get round this - sort of - would be to declare the class A as abstract, which would prevent instances of A being constructed, but even then the constructor for A will be called before the constructor for B (as you would expect, A has to be "complete" before B can use it) which would still mean that keyName is not initialised before Initial is called.

You can't do what you want: it just isn't possible because the class A constructor has to be complete before any derived class constructor code can be executed - and that applies equally to instance and static constructors.

What are you trying to achieve that you think you need this?
 
Share this answer
 

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