I am new to C# and trying to understand lambda expressions along with delegates. This is the code I am running:
delegate bool D1();
delegate bool D2(int i);
namespace Console
{
class Program
{
D1 d1;
D2 d2;
public void testMethod(int input)
{
int j = 0;
d1 = () => { j = 10; return j < input; };
d2 = (x) => { return x == j; };
System.Console.WriteLine("j = {0}", j);
bool res = d1();
System.Console.WriteLine("res={0}, j ={1}", res, j);
}
static void Main(string[] args)
{
Program p = new Program();
p.testMethod(10);
System.Console.WriteLine(p.d2(10));
System.Console.ReadKey();
}
}
}
What I don’t understand is the invocation of d2 prints true. When d2 was constructed value of j was 0. It was changed only after d1 was invoked later in the testMethod. So how it is printing True ? what am I missing here?
d1andd2both refer to the same instance ofj. When you setjby callingd1you’re also altering the value of the variable thatd2can see.If you want them do have different instance of
jyou’ll need to scope the variable:However, if you’re going to do this then you might as well have two different variables, say
j1andj2instead. This will be more readable.