Add warnings for initializers that reference other fields or properties in same type #893
Replies: 5 comments
-
Might be a candidate for warning waves, but I don't see the compiler ever being modified to make this illegal. |
Beta Was this translation helpful? Give feedback.
-
If I include an empty static constructor, the behavior doesn't change. So I don't think this is related to
It's not. The spec says (emphasis mine):
|
Beta Was this translation helpful? Give feedback.
-
This would be a breaking change. The language team are highly adverse to introducing breaking changes unless the benefits offered seriously outweigh the pain of breaking existing code. This proposal is extremely unlikely to happen therefore. |
Beta Was this translation helpful? Give feedback.
-
I've updated the proposal to add a warning instead of inducing a compilation fail and added language that this should apply to both static and instance field or property initializers. |
Beta Was this translation helpful? Give feedback.
-
@TylerBrinkley This would be a great candidate for an analyzer in the meantime. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Consider the following code.
One might expect
Singleton.Instance.Settings
to be equal to"The settings"
but sinceInstance
referencesDefaultSettings
which is declared afterInstance
, results innull
in my testing. If I declareDefaultSettings
aboveInstance
then I get"The settings"
.To reduce these issues I propose that warnings be added to recommend initializing the fields or properties within a constructor when referencing other fields or properties that may have not been initialized yet. This warning should apply to both static and instance field or property initializers.
Updates
beforefieldinit
and switched to proposing a warning instead of a compilation fail.Beta Was this translation helpful? Give feedback.
All reactions