What exactly causes the execution of a static constructor in C#? I'm testing with .NET 4.0 both in Windows and via Mono on Linux and I see the same behavior.
I always thought the first time that there was a reference to the class that it would trigger the code to run but with this demo, it appears it's more related to the first time there's a request to execute something on the class.
Can somebody please explain this a little more clearly? Also, other than the fact that lambda expressions haven't always been around, does this behavior change at all with different versions of .NET?
Code:
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Console.WriteLine("1. Main Started!");
Expression<Func<bool>> func = (() => Foo.ReturnFalse());
Console.WriteLine("2. Func func has been created.");
Console.WriteLine("3. Func func returns: " + func.Compile().Invoke());
}
}
public static class Foo
{
static Foo()
{
Console.WriteLine("?. Initializing Foo");
}
public static bool ReturnFalse()
{
return false;
}
}
Output:
1. Main Started!
2. Func func has been created.
?. Initializing Foo
3. Func func returns: False
What I expected:
1. Main Started!
?. Initializing Foo
2. Func func has been created.
3. Func func returns: False