"init" as a Modifier for Methods. #4454
Replies: 2 comments
-
See: https://github.com/dotnet/csharplang/blob/master/meetings/2020/LDM-2020-06-15.md#init-methods |
Beta Was this translation helpful? Give feedback.
-
You can already write methods that can be called from a constructor. Why not just return a value (or values) after performing your calculations and assign the return value to the properties/fields still within the constructor. That's reusable, can be called from multiple constructors and doesn't require any language changes. If you make it Now I understand that such methods might want to set the values directly and that |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Currently you can only set the value of readonly fields and auto-implemented get-only properties in the constructor of a class. Attempting to do so anywhere else will generate a compiler-error.
Now this can cause some issues when you have a number of get-only auto properties where you can't inline the initialization.
One example that comes to my mind are RelayCommands in ViewModels in MVVM Applications. Having the initilzation of all commands in the constructor of a ViewModel can get unwieldly, especially if there are other things that need to be done at initilzation.
I think a way to mark a method as an "initilzation method", which could only be called from a constructor and could in turn set the values for readonly fields and auto-implemented get-only properties, would be really helpful. That way I could keep the code in my constructor clean and high-level and also more reusable if I have multiple constructors. Even just having the ability to limit a method to only being callable from a constructor would also help to make your intent clearer and to enforce that intent.
And I think reusing the recently added "init" keyword as modifier for methods for that purpose would be just perfect. It keeps the same semantics of only being accesible at object initilzation and would be, in my opinion, very intuitive to understand.
Now since these methods would only be callable from the classes constructor, they'd necessairly have to be either protected or private methods. A public init method would not make much sense, since you wouldn't be able to call them on an instance of that class anyway. Whether a public init method would create a warning or an error, I'm not sure, but I'm leaning more toward error.
And since constructors cannot be async, allowing init methods to be async would probably also cause more trouble that it's worth. Although I'm not sure about that one.
Thoughts?
Beta Was this translation helpful? Give feedback.
All reactions