Reputation: 3494
In Delphi, you can define functions within functions, example :
function Foo : integer;
var myvar : integer;
function Foo1;
begin
myvar := 42;
end;
begin
result := myvar;
end;
This returns 42 as expected because Foo1 has access to Foo's myvar.
Is there any equivalent in C#?
Upvotes: 3
Views: 154
Reputation: 120518
Yes, there are many ways to do this. One way is to declare Func or Action delegates as follows:
void Foo()
{
Func<int,int> f = x => x+1;
//or
Func<int,int> ff = x => {
return x+1;
};
var r = f(1); //2
var rr = ff(2); //3
Func<int,int,int> add => (a,b) => a+b;
var rrr = add(2,3); //5
}
The shorthand declaration ( =>
) is commonly used in Linq. See lambdas.
There are many generic Func
and Action
delegates declared in the BCL (or whatever it's called nowdays) to allow for all but the stupidest length parameter lists. You could always declare your own generic delegates if you need more parameters.
Upvotes: 11