Why C# won’t allow field initializer with non-static fields?

I’m more interested with the reason/logic for why it was restricted. just for curiosity.

If you read the C# Language Spec, 10.11.3, it hints as to the rationale here. In discussing variable initializers:

It is useful to think of instance variable initializers and constructor initializers as statements that are automatically inserted before the constructor-body.

Since these are “inserted before the constructor”, they are being executed prior to this being valid, so allowing you to refer to other members (effectively this) would be problematic.

Note that this is consistent with how static fields work, as well. In both cases, you are allowed to access static data, but not instance data. The error message you receive (“A field initializer cannot reference the non-static field, method, or property”) directly notes this.

Leave a Comment