Initializer Method Attribute #8527
-
Sometimes it's cleaner to split your types initialization code into multiple methods, especially if your class is implemented in multiple files I propose to add a "InstanceTypeInitializerMethodAttribute" (or perhaps "ConstructorMethodAttribute", etc name debatable) attribute that signifies that this instance method is to be called within the an instance constructor which allows this method to assign get only properties and readonly fields. Example: class SomeType
{
public readonly int x;
public SomeType()
{
InitializeX();
}
public void IllegalMethod()
{
// error CSxxxx: cannot use initializer method here
InitializeX();
}
[InstanceTypeInitializerMethod]
void InitializeX()
=> x = 1; // imagine a more complex initialization here
} Right now, if someone wanted to use this structor, one would have to use unsafe code, avoiding readonly and get only or declaring If this has already been proposed before let me know. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Beta Was this translation helpful? Give feedback.
-
I agree this is a valid scenario but the most likely way we'd end up addressing it is with |
Beta Was this translation helpful? Give feedback.
#4238
#348
#1871
#1296