Brian Gordon Brian Gordon - 2 months ago 11
C# Question

Is there idiomatic C# equivalent to C's comma operator?

I'm using some functional stuff in C# and keep getting stuck on the fact that

List.Add
doesn't return the updated list.

In general, I'd like to call a function on an object and then return the updated object.

For example it would be great if C# had a comma operator:

((accum, data) => accum.Add(data), accum)


I could write my own "comma operator" like this:

static T comma(Action a, Func<T> result) {
a();
return result();
}


It looks like it would work but the call site would ugly. My first example would be something like:

((accum, data) => comma(accum.Add(data), ()=>accum))


Enough examples! What's the cleanest way to do this without another developer coming along later and wrinkling his or her nose at the code smell?

Answer

I know that this thread is very old, but I want to append the following information for future users:

There is a comma operator in C# 6.0 and higher - it is only called the semicolon operator, which is used like this:

int square = (int x = int.Parse(Console.ReadLine()); Console.WriteLine(x - 2); x * x);

which can be translated as follows:

int square = compiler_generated_Function();

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int compiler_generated_Function()
{
    int x = int.Parse(Console.ReadLine());

    Console.WriteLine(x - 2);

    return x * x;
}

which interestingly matches the F#-syntax very nicely:

let square =
    let x = match System.Int32.TryParse System.Console.ReadLine with
            | (true, x) -> printfn "%d" (x - 2)
                           x * x
            | (false, _) -> ... //do error handling here


Developers, which are using C# 5.0 or earlier do not have access to these features.