Conceptual reason of the 'A field initializer cannot reference the non-static field, method, or property' CS0236 Error
Asked Answered
H

2

6

C# does not allow an instance field initializer to reference another field. For instance this code is not valid :

class A
{
 string s1 = "";
 string s2 = s1;
}

because "s2" references "s1".

But why this is not permitted ?

My first thought was that the C# specs do not guarantee any initialization order but according to the specs the order is the order of declaration :

The variable initializers are executed in the textual order in which they appear in the class declaration.

So if the order is deterministic what could be the pitfalls of this kind of code ?

Thanks in advance for your help.

EDIT :

According to the answers of Hps, 0xA3 and Peter :

  • order of initialization in inheritance scenario could be very confusing,

  • implementing such a feature would require some resources from the compiler development team for little benefit,

  • it's not possible to use method or properties for logical reasons (thanks Peter), so for consistency the same is true for fields.

Housemother answered 26/11, 2010 at 14:5 Comment(1)
It's worth noting that vb.net runs field initializers after base-object construction, and does allow them to reference the object being constructed. I consider this a good thing, especially in cases where an invariant relationship exists among fields. It would be even better if exposing constructor parameters to field initializers were less clunky.Teenateenage
H
5

I'm not sure about a field, but it seems rational to deny field initializers access to properties or methods. For example:

class A
{
    string s1 = GetString();
    string s2 = this.MyString;
    string s3 = "test";

    public string GetString()
    {
        // this method could use resources that haven't been initialized yet
    }

    public string MyString
    {
        get { return s3; } 
        // this field hasn't been initialized yet 
        // (okay, strings have a default value, but you get the picture)
    }
}
Hunkydory answered 26/11, 2010 at 14:22 Comment(0)
B
2

The compiler probably could check the order of the fields and then allow initialization if the other field has been previously declared.

Besides the pitfall that re-ordering or re-structuring breaks your code, why should the compiler be unnecessarily complex. Resources are limited, and the compiler team probably prefers working on features with higher priority.

Basion answered 26/11, 2010 at 14:16 Comment(1)
Thanks for this remark. You must be right, the compiler team often justifies the lack of features by the lack of resources. Too bad that they have not more resources to make C# better than it is.Housemother

© 2022 - 2024 — McMap. All rights reserved.