Reputation: 1303
Inspired by JavaScript Closures I tried to Simulate Local static variables in C# using Func<> Delegate... Here is my code..
public Func<int> Increment()
{
int num = 0;
return new Func<int>(() =>
{
return ++num;
});
}
Func<int> inc = Increment();
Console.WriteLine(inc());//Prints 1
Console.WriteLine(inc());//Prints 2
Console.WriteLine(inc());//Prints 3
I am eager to know if there is any other way of simulating local static variable in C#? Thank You.
Upvotes: 4
Views: 509
Reputation: 6975
This is absolutely horrible, but one way would be to use an iterator method and discard the output. For example, if you wanted:
public void PrintNextNumber()
{
static int i = 0; //Can't do this in C#
Console.Out.WriteLine(i++);
}
You could instead write:
public IEnumerator<object> PrintNextNumber()
{
int i = 0;
while (true)
{
Console.Out.WriteLine(i++);
yield return null;
}
}
Then instead of calling PrintNextNumber()
, you'd do var printNext = PrintNextNumber(); printNext.MoveNext;
.
I really only wrote this answer for satisfying curiousity, I absolutely would not recommend really doing this!
It becomes even more nasty if you want to actually return something from the method but it's possible- you can yield return
instead, then retrieve it using Current
after having called MoveNext
Upvotes: 5