Kotlin's scope functions(.let, .also, .apply, etc) are super useful.
- let - Kotlin Programming Language
- also - Kotlin Programming Language
- apply - Kotlin Programming Language
I want to these methods in C#.
So I just define it!
static class ObjectExtensions
{
// Kotlin: fun <T, R> T.let(block: (T) -> R): R
public static R Let<T, R>(this T self, Func<T, R> block)
{
return block(self);
}
// Kotlin: fun <T> T.also(block: (T) -> Unit): T
public static T Also<T>(this T self, Action<T> block)
{
block(self);
return self;
}
}
Usage
var text = resultCode.Let(x => {
switch (x) {
case 0:
return "success";
default:
return $"error({x})";
}
});
var model = new MyModel().Also(m => {
m.Initialize();
m.Load(path);
});
I hope .NET Framework provide these methods.
Top comments (4)
Please, didn't you by chance ask Microsoft team when scope functions will be in C#?
C# really need this.
I have hard times to come back from Kotlin to C#. Kotlin is just so much more effective language.
I also miss keyword "val". It's just so elegant. And I would discard keyword "new".
And after your suggestions are accepted and implemented the language will be called k# (keesharp, kosharp).
Why not suggesting here: github.com/dotnet/csharplang
I want multiple inheritance and templates like in C++ with specializations.
Nice. Thanks