Quiz: Type Constructors
Clearly this code should fail a code review but what would calling PrintValue() display?
public class Foo
{
public static int Value = 42;
static Foo()
{
Value = 17;
}
public static void PrintValue ()
{
Console.WriteLine(Value);
}
}
Same, question, but in VB:
Class Foo
Public Shared Value As Integer = 42
Shared Sub New()
Value = 17
End Sub
Public Shared Sub PrintValue()
Console.WriteLine(Value)
End Sub
End Class
Even more importantly, assuming we want Value to be initialized to 63, what is the best code and why?
Setting the static field in line:
public class Foo
{
public static int Value = 63;
public static void PrintValue ()
{
Console.WriteLine(Value);
}
}
Or using a type constructor:
public class Foo
{
public static int Value;
static Foo()
{
Value = 63;
}
public static void PrintValue ()
{
Console.WriteLine(Value);
}
}