Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - analogue of with keyword from Kotlin?

Tags:

c#

kotlin

I want to something like with keyword in Kotlin to reduce the amount of repeated code like that:

fun printAlphabet() = with(StringBuilder()){
    for (letter in 'A'..'Z'){
        append(letter)
    }
    toString()
}

Any facilities?

like image 226
Дима Соколов Avatar asked Dec 06 '25 19:12

Дима Соколов


1 Answers

You can do this with With methods like this:

// you need a separate overload to handle the case of not returning anything
public static void With<T>(T t, Action<T> block) {
    block(t);
}

public static R With<T, R>(T t, Func<T, R> block) => block(t);

And then you can using static the class in which you declared the methods, and use it like this (translated code from here):

var list = new List<string> {"one", "two", "three"};
With(list, x => {
    Console.WriteLine($"'with' is called with argument {x}");
    Console.WriteLine($"It contains {x.Count} elements");
    });
var firstAndLast = With(list, x => 
    $"The first element is {x.First()}. " +
    $"The last element is {x.Last()}.");

In your example, it would be used like this:

static string PrintAlphabet() => With(new StringBuilder(), x => {
        for (var c = 'A' ; c <= 'Z' ; c = (char)(c + 1)) {
            x.Append(c);
        }
        return x.ToString();
    });
like image 127
Sweeper Avatar answered Dec 08 '25 07:12

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!