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?
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:
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.
Yeah, it does matter when interfacing with unmanaged code.
I believe XmlSerializer serializes members in the order they appear in the source file.
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.
I was primarily thinking about the order of initialization, yes - particularly for static fields. For instance (with public fields just for simplicity of demonstration):
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.
Here is a classic example from the C# language spec (Section 10.5.5)
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.