Is there a C# equivalent to the Python := (an assignment expression)?

Question:

Assignment expression Python 3.8

I like how it saves line. Example:

for rule in rules:
    place = getPlace(rule)
    if place:
        print(f"Apply rule {rule.__name__} -> {place}")
        return place
raise Exception('No rule found!')

↓↓

for rule in rules:
    if place:= getPlace(rule):
        print(f"Apply rule {rule.__name__} -> {place}")
        return place
raise Exception('No rule found!')

Is there a C# equivalent or it needs to use variable assignment on the line before?

Asked By: Daniel Novák

||

Answers:

Well, there isn’t a perfect 1:1 match, but in your case you could use

foreach (var rule in rules)
{
    string place;
    if ((place = GetPlace(rule)) != null)
    {
        Console.WriteLine($"Found {place}");
        return place;
    }
}

Here is a demo. The ((place = GetPlace(rule)) != null) is only used very rarely in C#, a more idiomatic way would be to make the GetPlace return a bool indicating success and a out parameter like so (naming convention would also tell us to name this method TryGetPlace)

public bool TryGetPlace(string rule, out string place)

Setting place to a value and returning true if successful, and returning false if not, you’d then use it like so:

foreach (var rule in rules)
{
    if (TryGetPlace(rule, out var place))
    {
        Console.WriteLine($"Found {place}");
        return place;
    }
}
Answered By: MindSwipe