Can I expect that c# will execute this two lines in this order each time it is run?
Yes, instance variable initializers when legal (see below) run in the order in which they appear. I refer you to section §10.11.2 of the specification:
This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor. The variable initializers are executed in the textual order in which they appear in the class declaration.
However, a field initializer can not reference a non-static field as you have done. Your code is not legal. This is §10.5.5.2 of the specification:
A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple-name.
Regarding your second question:
Or should I put this initializations in constructor?
Per the above, you have no choice. At a minimum you must put the initialization of myReadOnlyList
in the constructor as it refers to the instance field myList
. For clarity, I would put both in the constructor.
One last note, on a separate issue. Even the following is not legal:
public class MyClass {
private List<T> myList;public class MyClass
private ReadOnlyCollection<T> myReadOnlyList;
public MyClass() {
myList = new List<T>();
myReadOnlyList = myList.AsReadOnly;
}
This is because you have not declared MyClass
as a generic class. Replace public class MyClass
with public class MyClass<T>
.