C#, Lambdas, closures, value types

Blogging this in order that I remember in the future that I have been around this “loop” many times and that this code;

            int x = 1;
            
            Action a = new Action( ( ) =>
            {
                x++;
            });
            
            a(  );
            
            Console.WriteLine( x );

prints a value of 2 whereas this code;

            int x = 1;
            
            Action<int> a = new Action<int>( ( i) =>
            {
                i++;
            });
            
            a( x );
            
            Console.WriteLine( x );

prints a value of 1 and that means that this code;

    struct MyStruct
    {
        public void Set()
        {
            flag = true;
        }
        public void Print()
        {
            Console.WriteLine(flag);
        }
        public bool flag;
    }
    class Program
    {
        static void Main(string[] args)
        {
          MyStruct myStruct = new MyStruct();
          
          Action action = new Action ( () =>
          {
            myStruct.Set();
          });                
          action();
          
          myStruct.Print();
                  
        }
    }

prints a value of true whereas this code;

    struct MyStruct
    {
        public void Set()
        {
            flag = true;
        }
        public void Print()
        {
            Console.WriteLine(flag);
        }
        public bool flag;
    }
    class Program
    {
        static void Main(string[] args)
        {
          MyStruct myStruct = new MyStruct();
          
          Action<MyStruct> action = new Action<MyStruct> ( (ms) =>
          {
            ms.Set();
          });                
          action(myStruct);
          
          myStruct.Print();
                  
        }
    }

prints a value of false.

Now…let me never forget that sort of stuff again and have to open up ILDASM to figure it all out once more.

I hope I wrote it down correctly above 🙂