Friday, February 22, 2013

Struct is mutable?? Think again !!


Struct is value type defined in .Net and is actually mutable (means if I change member variable of struct it really get changed and do not
create new copy). Same thing is not true about String.
for ex, String str = "Hello";
str = str + "John";
The above operation would create new copy of string str and store in it "Hello John". Hence strings are immutable.

In case of struct,
struct rectangle
{
private int length;
public int Length
{
get
{
return length;
}
set
{
length = value;
}
}
private int width;
public int Width
{
get
{
return width;
}
set
{
width = value;
}
}

public void display()
{
Console.WriteLine("Length= {0} Width = {1}",length,width);
}
        }

public static void Main()
        {

            rectangle r = new rectangle();
            r.Length = 10;
            r.Width = 20;
            r.display();
            //Length= 10 Width = 20

            r.Length = 400;
            r.display();
            //Length= 400 Width = 20
         
           //Here actual struct variable (r) is modified and displayed.


            List Room = new List();
            Room.Add(new rectangle { Length = 5, Width = 10 });

           
            foreach (rectangle item in Room)
            {
                item.display();
            }

            //Length= 5 Width = 10

            //Room[0].Length = 20;   //error
            Room[0] = new rectangle { Length = 20, Width = Room[0].Width };

            foreach (rectangle item in Room)
            {
                item.display();
            }
            //Length= 20 Width = 10

            rectangle[] walls = new rectangle[2];

            walls[0] = new rectangle { Length = 10, Width = 30 };

            walls[0].display();

            //Length= 10 Width = 30
           
            walls[0].Length = 40;

            walls[0].display();
            //Length= 40 Width = 30
         
        }

So, if a struct is part of collection class (List), it is not possible to directly change
properties of struct variable, we have to use workaround as shown below

//Room[0].Length = 20;   //error
               Room[0] = new rectangle { Length = 20, Width = Room[0].Width }; // work around

In case of struct part of Array[], we can modify properties of struct as normal variable.

So this is the case where actual struct variable can not modified.

Monday, February 18, 2013


Try hands on LINQ http://www.wiziq.com/online-tests/41952-linq-test-1

Basic c# quiz http://www.wiziq.com/online-tests/43860-c-basic-quiz