views:

346

answers:

7

This question is inspired by Jon Skeet's answer: http://stackoverflow.com/questions/431091/is-there-a-c-equivalent-to-cs-access-modifier-regions#431105

He makes a comment that it is possible for the order of fields in a file to matter. I am guessing that this has to do with the order that the fields are initialized, but I think it's a dangerous enough thing to code based on this side effect that it warranted its own question and discussion.

Are there other thoughts around how the order of fields within your code file could be manipulated and what impact that might have?

+3  A: 

Yeah, it does matter when interfacing with unmanaged code.

Mehrdad Afshari
Ok yea I knew that but it slipped my mind isn't there a LayoutKind attribtue as well..to tell the compiler to organize the fields in a specific order.
JoshBerke
@Josh, There is but it's much easier to declare them in the correct order
JaredPar
+2  A: 

I was primarily thinking about the order of initialization, yes - particularly for static fields. For instance (with public fields just for simplicity of demonstration):

using System;

class First
{
    static int a = 10;
    public static int b = CalculateB();
    static int c = 5;

    static int CalculateB()
    {
        return a*c;
    }
}

class Second
{
    static int a = 10;
    static int c = 5;
    public static int b = CalculateB();

    static int CalculateB()
    {
        return a*c;       
    }
}

class Test
{
    static void Main()
    {
        Console.WriteLine("First.b: {0}, Second.b: {1}",
                          First.b, Second.b);
    }
}

The order of initialization is defined in the spec to be the textual order in which the variables are declared - but it becomes undefined when two variables are in different files contributing to a partial class.

Mehrdad's answer is another good one: anything where physical layout is important will quite possibly be affected by declaration order.

Jon Skeet
Thanks for expanding on your comment;-) This is what I figured just would not have been able to express it so well.
JoshBerke
+1  A: 

If fields are initialized as part of the declaration, they are added to the constructor (instance or static) in the order they appear in the file.

Brian Rasmussen
+20  A: 

Here is a classic example from the C# language spec (Section 10.5.5)

class Test
{
    static int a = b + 1;
    static int b = a + 1;
    static void Main() {
     Console.WriteLine("a = {0}, b = {1}", a, b);
    }
}

This is a completely valid program and as written (a = 1, b =2). However if you swap the ordering of the fields they will also swap values.

JaredPar
I was surprised this compiled - I expected the compiler to detect the use of an initialized field (whereas my more complicated example would have been harder to spot). That's a nice concise demo.
Jon Skeet
Awesome example.
Mehrdad Afshari
I would have never thought this compiled...
JoshBerke
Interestingly, it doesn't in Java.
Jon Skeet
@Jon, i was quite surprised as well the first time I saw this example.
JaredPar
@Jon: Fields are never uninitialized, only local variables (and out params). Fields (static or otherwise) are always default initialized. In practice, this means that the entire memory area containing the fields is zeroed out prior to running initializers and the constructor.
P Daddy
... This is why structs cannot have instance field initializers. It would break the zero-out-to-default-initialize behavior.
P Daddy
Nice example - came as a surprise to me.
RoadWarrior
A: 

You can use (abuse?) the order of fields as metadata of your class which you can than read via reflection.

for example, if you have a class that represents a network protocol with fields ID, PORT, and XOR, in that order, you could define it as:

class MyProtocol {
    int ID;
    int PORT;
    int XOR;
}

Now suppose you use reflection to iterate the fields of the protocol, to send over the wire. The order returned by GetProperties will be as you defined, and you didn't have to write any extra metadata explicitly.

Not sure if it's a good idea though to depend on this.

Roy Peled
A: 

I believe XmlSerializer serializes members in the order they appear in the source file.

Joe
A: 

[deleting my previous "Answer", since it really is a new question.]

Eric Hirst