Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
struct Employ
    {
        static string Pass;
        int id;
        string name;
        static Employ()
        {
            Pass = "Word";
            Console.WriteLine("creat static constructor Employ ");
        }
        public Employ(string _name,int _id)
        {
            name = _name;
            id = _id;
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            Employ Ob = new Employ("mohamed", 10);

        }
    }


why when i creat variable from struct employ the compiler not access the static constructor ??
Posted

I just tried the code you posted and the static constructor is correctly called right before the non-static constructor is called.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 18-Feb-13 13:41pm    
Of course, but OP asks about "access" of static constructor. Probably, it needs extra explanation. I voted 5, but... can you explain why one cannot call it? The answer is apparent but explaining it... boring stuff, anyway.
—SA
It definitely access static constructor. But only for first time when the "Employ" strut instance is created. if you trying to create new instance second time it will not access. A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only

http://msdn.microsoft.com/en-us/library/k9x6w0hc(v=VS.80).aspx[^]
 
Share this answer
 
The static constructor is not called because in your Main method you don't reference any static member of the Employ class (see Static Constructors[^]: A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

change
Quote:
static string Pass;
to
public static string Pass;


and add the following line to your Main method
C#
Console.WriteLine(Employ.Pass);

To see the static constructor called.
 
Share this answer
 
Because of you can not create object of any static member.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 18-Feb-13 13:38pm    
This is not a correct explanation. In fact, there is nothing which prevents using static constructors. The structure is not static, read carefully, so you can create a member.
Sorry, I don't understand how can you have 61 answer if you simply have no clue on programming...
—SA
Marco Bertschi 18-Feb-13 16:23pm    
I had a look at his answers too. I am not considering to be the last instance nor a judge but to me it seems like he is giving just general answers or posting general links instead of really answering a question. Or the answer is just wrong (like this one is).

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