Reputation: 923
What is this called in c#? And how do you do it/syntax? Is this called an "inline function"?
I'm in a method. In this method I want to re-use the same bit of code a few times. Perhaps as a variable as you can in other languages.
e.g.
// I have a bit of code to define an expression expl
line1: int x = 0;
line2: var expl = { x+=2 }
line3: ... use expl // x now =2
line4: ... use expl // x now =4
line5: ... use expl // x now =6
line6: ... ... do other things ...
line7: ... use expl
... and so it goes on
Unlike my pseudo-code above, my expression is rather lengthy and I don't fell like I should have to create a function out of it, yet. In this method is the only place in the application the expression (for my lack of a better term at the moment) will never be used.
Please understand I am not simplistically just trying to add 2 to x in my production expression. I would do that on each of the lines using x
. In production expl
is actually a five line ternary expression (I believe I am using the term expression correctly in this case) so I don't what to just cut-and-past the same five lines over and over :-)
Thanks.
Upvotes: 1
Views: 81
Reputation: 4443
The term you are looking for is "anonymous function" or "lambda expression".
The easiest way to what you want to do is using the Action<>
or Func<>
generic delegate types. If you want to return a value, use Func<>
, to return void use Action<>
.
In your example, you could write the expression line like so:
Func<int> expl = () => x += 2;
This will add 2 to x
and return the result.
Upvotes: 1
Reputation: 156524
int x = 0;
Action addTwo = () => x += 2;
addTwo();
addTwo();
Action
is a specific form of delegate
, which is like an inline function. The fact that it uses a variable declared outside of its own scope makes it a closure as well. Other delegate
s that are defined with the .NET framework include various generic forms of Action<>
(so you can pass parameters into it), and Func<>
(so you can return a value from it). But you can also declare your own named delegate that has any method signature you like.
The above code uses a lambda expression, or lambda syntax, but you can also declare it more explicitly:
Action addTwo = delegate() { x += 2 };
The yet-to-be-released C# 7 is expected to have Local Functions, which is essentially the same thing, but with slightly different syntax:
void AddTwo() => x += 2;
or
void AddTwo() { x += 2; }
Upvotes: 3