Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 874
Rag Avatar asked Aug 18 '11 21:08

Rag


People also ask

What is an idiom in C?

The idiom is that if you have a void * value of known type, you immediately assign it to a variable of that type. No explicit cast is needed.

What is a language specific idiom?

An "idiom" in (non-programming) language is a saying or expression which is unique to a particular language. Generally something which doesn't follow the "rules" of the langauge, and just exist because native speakers "just know" what it means. (

What is a Python idiom?

Idiomatic Python is what you write when the only thing you're struggling with is the right way to solve your problem, and you're not struggling with the programming language or some weird library error or a nasty data retrieval issue or something else extraneous to your real problem.


2 Answers

I know this as Fluent.

A Fluent example of a List.Add using Extension Methods

static List<T> MyAdd<T>(this List<T> list, T element) {     list.Add(element);     return list; } 
like image 146
devio Avatar answered Sep 21 '22 06:09

devio


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

There isn't currently such an operator. During the C# 6 development cycle a semicolon operator was added, as:

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

However, this feature was dropped before the final C# release.

like image 30
unknown6656 Avatar answered Sep 18 '22 06:09

unknown6656