1

Looking at well known CS0236 error message

Error (CS0236): A field initializer cannot reference the nonstatic field, method, or property and the

reason for such restriction is intialization order:

You cannot use an instance variable to initialize another instance variable.

But this is not an instance variable, is it? My question is why there is such strict requirement even for refrencing class methods? In my understanding, it would suffice to restrict just invocation of class methods, e.g.:

bool _field;
bool GetField() => _field;
bool _field2 => GetField(); // clearly an error, invoking something that might not be initialized
// why compiler cannot safely bind a delegate? It does not have to access anything, just take an address
Func<bool> Func1 = GetField; // does not have to error, refencing but not invoking

Is this just a design decision or are there any technical limitations that prevent delegate binding during field initialization?


Edit: I am interesed in the technical aspects, rather than bugfixing. What prevents the compiler binding the instance method? Address of this must be avaialable at the point when binding happens and something like funcPtr = instanceaddress+memberoffset does not seem to have any side effects on initialization.

wondra
  • 3,271
  • 3
  • 29
  • 48
  • Possible duplicate of [What does "a field initializer cannot reference non static fields" mean in C#?](https://stackoverflow.com/questions/923343/what-does-a-field-initializer-cannot-reference-non-static-fields-mean-in-c) – György Kőszeg Nov 08 '19 at 12:14
  • @GyörgyKőszeg that does not answer why evaluating expression like `bool (*delegate)() = &this + offsetof(GetField)` is not technically possible for the compiler when initializing a class. Except of the address of the instance being constructed (it must be have been allocated before contruction begun!) it is all static. Any insights? – wondra Nov 08 '19 at 13:11
  • 1
    _What prevents the compiler_ - nothing else but the decision of the C# compiler team. This has nothing to do with the reference of `this` (which is not even applicable for a `struct`). As Eric Lippert says in the comment under the linked post this is just for preventing accidental use of an uninitialized object. Of course, in your case the delegate is not passed as a parameter to any member, which could invoke it before finishing the construction; still, they don't perform such a deep analysis on the initializer expression. Put such inits in the constructor body and you are fine. – György Kőszeg Nov 08 '19 at 14:37

0 Answers0