Proposal: init only methods #4218
-
Since we have init-only properties, can we also have init-only methods? I imagine the syntax would be like: class MyClass
{
public int Value { get; init; }
public init void EnableSomeFunction() { } //Maybe void here can be omitted?
}
var obj = new MyClass()
{
Value = 1,
EnableSomeFunction(),
}; This is to solve the "return this" methods, e.g., that constructs an instance of some service. There are plenty of such examples. One in the Avalonia UI: public static AppBuilder BuildAvaloniaApp()
{
return AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToDebug()
.UseReactiveUI();
} may be written instead as: public static AppBuilder BuildAvaloniaApp()
{
return new AppBuilder
{
Configure<App>(),
UsePlatformDetect(),
LogToDebug(),
UseReactiveUI(),
};
} Advantages:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
I like this in general. Would it be possible to use return values of init methods inside init block? It would feel artificial if you can't, but if you can, it means we need init-block-local variables as well? You would want them for init methods with 'out' parameters as well. |
Beta Was this translation helpful? Give feedback.
-
This was discussed at a language design meeting back in June: TL;DR:
|
Beta Was this translation helpful? Give feedback.
This was discussed at a language design meeting back in June:
https://github.com/dotnet/csharplang/blob/master/meetings/2020/LDM-2020-06-15.md#init-methods
TL;DR: