Using Func delegate we can achieve Closure in C#.
static void Main(string[] args)
{
var inc = GetAFunc();
Console.WriteLine(inc(5));
Console.WriteLine(inc(6));
}
public static Func GetAFunc()
{
var myVar = 1;
Func inc<int,int> = delegate(int var1)
{
myVar = myVar + 1;
return var1 + myVar;
};
return inc;
}
Or you can write with lambda
public static Func GetAFunc()
{
var myVar = 1;
Func inc <int,int> = (var1)=>
{
myVar = myVar + 1;
return var1 + myVar;
};
return inc;
}
Output
7
9
static void Main(string[] args)
{
var inc = GetAFunc();
Console.WriteLine(inc(5));
Console.WriteLine(inc(6));
}
public static Func
{
var myVar = 1;
Func
{
myVar = myVar + 1;
return var1 + myVar;
};
return inc;
}
Or you can write with lambda
public static Func
{
var myVar = 1;
Func
{
myVar = myVar + 1;
return var1 + myVar;
};
return inc;
}
Output
7
9
No comments:
Post a Comment