Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the order of fields in C# matter?

This question is inspired by Jon Skeet's answer: Is there a c# equivalent to c++'s access-modifier regions

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?

like image 973
JoshBerke Avatar asked Nov 27 '22 08:11

JoshBerke


2 Answers

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.

like image 177
JaredPar Avatar answered Nov 30 '22 22:11

JaredPar


Yeah, it does matter when interfacing with unmanaged code.

like image 25
mmx Avatar answered Nov 30 '22 23:11

mmx