C # operator

Back in school, we wrote a compiler in which curly braces had the default behavior to execute all expressions and returned the last value ... so you could write something like:

int foo = { printf("bar"); 1 }; 

Is there something equivalent in C #? For example, if I want to write a lambda function that has a side effect.

The point is less about the lambda effect (just an example), more if there is this function ... for example, in lisp, you have progn

+6
scope c # curly-braces
source share
5 answers

Basically, Vladโ€™s answer is correct, and you donโ€™t need to declare the lambda function in advance as a delegate.

Also, in C #, the situation is not so simple, because the compiler cannot decide whether the syntax lambda expression should be compiled as a delegate (e.g. Func<int> ) or an expression tree (e.g. Expression<Func<int>> ), and It can also be any other compatible type of delegation. So you need to create a delegate:

 int foo = new Func<int>(() => { Console.WriteLine("bar"); return 1; })(); 

You can simplify the code a bit by specifying a method that just returns a delegate and then calling a method - the C # compiler automatically infers the delegate type:

 static Func<R> Scope<R>(Func<R> f) { return f; } // Compiler automatically compiles lambda function // as delegate and infers the type arguments of 'Scope' int foo = Scope(() => { Console.WriteLine("bar"); return 1; })(); 

I agree that this is an ugly trick that cannot be used :-), but it is an interesting fact that it can be done!

+7
source share

There is nothing stopping you from having side effects in lambda expression.

 Func<int> expr = () => { Console.WriteLine("bar"); return 1; }; int foo = expr(); 
+7
source share
 int foo = (() => { printf("bar"); return 1; })(); 

Edit: thanks for the constructive criticism, it should be

 int i = ((Func<int>)(() => { printf("bar"); return 1; }))(); 
+5
source share

We considered the possibility of creating shorter syntaxes than ()=>{M();} for defining a lambda, but could not find a syntax that reads well and is not confused with blocks, collection / object initializers, or array initializers. You are currently stuck in lambda syntax.

+3
source share

You are talking about an anonymous function: http://msdn.microsoft.com/en-us/library/bb882516.aspx , I think.

+2
source share

All Articles