I have two private lists that need to be initialized when object is created. Second list is dependent on first one. Can I do it like this:
public class MyClass
{
private List<T> myList = new List<T>();
private ReadOnlyCollection<T> myReadOnlyList = myList.AsReadOnly;
...
}
Second list is read only wrapper around first one.
Can I expect that c# will execute this two lines in this order each time it is run?
Or should I put this initializations in constructor?
Edit:
Sorry for stupid question. I tried it and compiler says:
Error 1 A field initializer cannot reference the
non-static field, method, or property...
No. If you want to initialize a variable based on a separate variable within the class, you need to do this in the constructor:
Inlined intializers are always run in a static context, which means you have no access to member variables within your class. Inside of a constructor, however, you can do this. The inlined initializers will occur before your constructor, which is why I could leave the list initialization in place.