Reputation: 10236
My code is as follows
class MyStaticClass
{
static MyStaticClass{};
public static readonly MyStaticClass Instance = CreateMe();
public static int GetSomeValue = GetValue();
private static int GetValue()
{
return 0;
}
private static MyStaticClass CreateMe()
{
Console.WriteLine("This method was called");
return new MyStaticClass();
}
}
public class Program {
public static void Main()
{
int val=MyStaticClass.GetSomeValue;
}
}
O/p:
This method was called
When I call val
why does the debugger accesses CreateMe
method ? Is it that any static method I access it will access all the static methods in the class ?
Upvotes: 2
Views: 89
Reputation: 2861
You have a static initializer for a static field. As part of program startup, all static fields are evaluated.
Edit: small clarification here:
The static fields in a particular class are evaluated in declaration order, but there in no particular order for which class has it's static fields initialized first. Now, if you had a static property, that would be different.
Upvotes: 1
Reputation: 3697
Both fields have been initialized using the static methods. So, in that case, all the static methods will be evaluated.
Upvotes: 0
Reputation: 148110
The method CreateMe()
is called because you are calling in when you create object Instance
in the following statement.
public static readonly MyStaticClass Instance = CreateMe();
This is static object in your class and is created as you access the class which you did by MyStaticClass.GetSomeValue
.
Dubugging the code will give you clear view of the order of the statements get executed. You can go through this detailed article on MSDN regarding debugging Debugger Roadmap
Upvotes: 4