Reputation: 8765
I have the following class:
class Foo
{
public Foo()
{
Console.WriteLine("Foo");
}
public string A { get; set; } = GetStr("A");
public string B { get; set; } = GetStr("B");
public static string GetStr(string str)
{
Console.WriteLine(str);
return str;
}
}
when I create an instance from it, the output is this:
A
B
Foo
if I change the of my properties to:
public string B { get; set; } = GetStr("B");
public string A { get; set; } = GetStr("A");
the output is:
B
A
Foo
My Question is:
Does order of properties in a class important and may effect my program?
Note: I use C# 6.0 new feature: Property initializer More
Upvotes: 0
Views: 950
Reputation: 556
In my experience (in C#), when using reflection, the order of the fields is returned as they are listed in the class (so it may be important).
For example:
public class TestClass
{
// purposely not in alphabetical order and of different types.
public string C { get; set; }
public int A { get; set; }
public string B { get; set; }
}
and then create an instance and assign values:
TestClass testObject = new TestClass();
// purposely not in same order as in class
testObject.B = "1";
testObject.C = "2";
testObject.A = 3;
and finally loop through properties:
foreach (PropertyInfo prop in typeof(TestClass).GetProperties())
{
Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(testObject, null));
}
prints out the following:
C = 2
A = 3
B = 1
The result is the same order as in the class definition.
Upvotes: 2
Reputation: 106
Order of properties doesn't matter. Your constructor call the GetStr
method which writes the string in console. Because of that order of properties seem change.
Upvotes: 0
Reputation: 292745
Field (and property, since C# 6) initializers are run first, in the order in which they are declared, then the constructor is executed.
So yes, the order of the properties affects the order in which they will be initialized; but the constructor will always be executed last.
Upvotes: 7