C# - analogue of with keyword from 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?

Upvotes: 3

Views: 150

Answers (1)

Sweeper
Sweeper

Reputation: 271355

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();
    });

Upvotes: 2

Related Questions