Why does not compiler compliain about non-initialized reference type members declared in structs? #6734
-
Not complaining.
Emits CS8618 warning. Yes, I understand, that record can be created without init logic of constructor being called, but that means the default value is semantically invalid. I've declared Isn't it more correct to require all ref types in structs be nullable? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 15 replies
-
NRT balances usefulness with accuracy. We deemed it too obnoxious to have to always nah Mark this as nullable and then have to deal with that at use sites. As most code doesn't run into default structures it was just onerous and massively increased the noise versus the signal. You can of course create an analyzer here trivially that would require you to make these all nullable and then have to deal with all the fallout. |
Beta Was this translation helpful? Give feedback.
-
Was it considered to track the state of struct as being default or not? Maybe, an attribute on method parameters and such: struct Struct { public Struct() { this.Str = "abc"; } public string Str; }
void Foo(Struct s)
{
int l = s.Str.Length; // NRT warning
}
void Bar([NotDefault] Struct s)
{
int l = s.Str.Length; // no NRT warning
}
Struct s = default;
int l = s.Str.Length; // NRT warning
Foo(s); // no NRT warning
Bar(s); // NRT warning
s = new Struct();
int l2 = s.Str.Length; // no NRT warning
Foo(s); // no NRT warning
Bar(s); // no NRT warning
// etc. |
Beta Was this translation helpful? Give feedback.
NRT balances usefulness with accuracy. We deemed it too obnoxious to have to always nah Mark this as nullable and then have to deal with that at use sites. As most code doesn't run into default structures it was just onerous and massively increased the noise versus the signal.
You can of course create an analyzer here trivially that would require you to make these all nullable and then have to deal with all the fallout.