1) Why must initialization value of field members be determinable at compile time?
2) But if the initialization value needs to be determined at compile time, then why am I able to initialize a A.b field using a reference to an object:
class A
{
B b = new B();
}
class B {}
Thank you
I’m a bit confused; there is no such rule for fields. In particular, fields are explicitly initialized anyway – either by your code, or to the type’s default. The only corner-case is explit struct field initialization, in which all fields must be assigned before the struct is considered complete.
I wonder if you are talking about “definite assignment” of variables within methods; i.e.
This is so that for method variables the values never suffer from random values picked up from the stack. Actually, there is an IL marked that means that locals are wiped – and IIRC the C# compiler includes this marker anyway… but the language spec says method variables must be definitely assigned.
In the case of you example, that field-initialization essentially becomes part of the common constructor code. But you’d never notice it.