I am a C++ programmer learning C#. I am currently reading C#4.0 in a Nutshell.
I have come accross this statement/snipet on page 74:
Static field initializers run in the
order in which the fields are
declared. The following example
illustrates this: X is initialized to
0 and Y is initialized to 3.
class Foo
{
public static int X = Y; // 0
public static int Y = 3; // 3
}
I dont understand how X can be assigned the value in Y, without Y being first declared. Am I missing something here?
As an aside, coming from a C++ background, I tend to use the term ctor for constructor – however, I haven’t yet come accross the term in C# – is the term ctor also used in the C# world?
[Edit]
A further example on the same page (in the book mentioned earlier) is this:
class Program
{
static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
public static Foo Instance = new Foo();
public static int X = 3;
Foo() { Console.WriteLine (X); } // 0
}
The book states (for the example above):
The example prints 0 followed by 3
because the field initializer that
instantiates a Foo executes before X
is initialized to 3:
I have some further questions w.r.t the examples.
-
Both examples appear under the section entitled Static constructors and field initialization order however, the code examples dont show a static ctor – atleast, not one that I can easily recognise. I was expecting a static ctor to have the same name as the class, be parameterless and be preceeded by the ‘static‘ keyword. So I dont see how the examples relate to the section heading. What am I missing here?
-
In the second example, the (non static) ctor prints out the value of X – which had explicitly been assigned the value of 3 in the previous line – and yet, the output printed out is 0. Why?!
In C#, primitive types such as
inttake on a default value. Forint, the default value is 0. This is not like C++ where you have to initialize the value or it will be getting a random dirty value from memory. Since Y is known to be of typeint, X can be assigned it’s default value of 0.As far as the keyword
ctor, I don’t see it used very much as a C# programmer, but I am familiar with the term. I believe it is used in a few places in Visual Studio, for instance in the object browser.