Mike Taulty's Blog
Bits and Bytes from Microsoft UK
C#, Lambdas, closures, value types

Blogs

Mike Taulty's Blog

Elsewhere

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 :-)


Posted Fri, Jan 16 2009 4:49 AM by mtaulty
Filed under: ,

Comments

Jason Haley wrote Interesting Finds: January 16, 2009
on Fri, Jan 16 2009 6:32 AM
Dew Drop – January 17, 2009 | Alvin Ashcraft's Morning Dew wrote Dew Drop &ndash; January 17, 2009 | Alvin Ashcraft's Morning Dew
on Sat, Jan 17 2009 6:27 PM
DotNetShoutout wrote Mike Taulty's Blog : C#, Lambdas, closures, value types
on Thu, Jan 22 2009 1:25 AM

Thank you for submitting this cool story - Trackback from DotNetShoutout

Recreational viagra. wrote Re viagra cello.
on Thu, Apr 2 2009 9:15 AM

Viagra. Women s viagra. Viagra on line. Free viagra. Your viagra onlinne guide. Re viagra cello. Herbal viagra.