tags:

views:

143

answers:

3

On MSDN I found:

In C#, every executed instruction is done so in the context of a method.

But I also read that an int A=5; statement can be in the class body. It seems it's not in a method body, so why this is possible? It is probably just term confusion but I would like to know.

+6  A: 
class Example
{
    int A = 5;
}

is equal to

class Example
{
    int A;

    public Example()
    { 
        A = 5;
    }
}

So the assignment is still part of a method (the constructor).

Adrian Godong
This can be proven by the way *readonly* marked fields can be assigned in the class definition OR in the constructor (only).
Michael
@Michael - that *supports* it, but it isn't proof. The proof is simply: that is how the language spec allows.
Marc Gravell
Actually that isn't quite a true representation; iirc field initialisers get invoked *before* the base ctor call. C# has no way of expressing that though -regular ctor bodies happen *after* the base ctor call.
Marc Gravell
It was referencing the equality example stated above - and in no way was attempting to define the specification itself or out the IL is generated from the two examples above. Are you attempting to read more into my statement....?
Michael
+1  A: 

You are probably referring to field initializations:

class Foo
{
    private static int i = 5;
}

Even this instruction runs inside the context of a method. In this particular case it is the static constructor. If the field is not static then it will be the normal constructor.

Darin Dimitrov
+8  A: 

Adrian is correct. To clarify further: "int A = 5;" is only a statement when it is inside a method body. When it is outside a method body then it is a field declaration with an initializer, which is logically moved into the constructor body.

The exact semantics of how the initializers work is a bit tricky. For some thoughts on that, see:

http://blogs.msdn.com/b/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx

http://blogs.msdn.com/b/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx

Eric Lippert