Friday 23 July 2010

Objects in C# by reference

I had a really nice discussion with my colleague last week and I made a very simple to prove the code. This actually proves that the objects in C# are copied by reference. So for example if I have an object defined with new keyword and set to other object of same type by changing first I am changing others as well.

Let take this example here:

I defined a class of Animal:

public class Animal

{

public int Id { get; set; }

public string Description { get; set; }

public Animal(int id,

string description)

{

this.Id = id;

this.Description = description;

}

}

This class I just added in Console application to observe the output and wrote the following code in Program.cs

static void Main(string[] args)

{

Animal Dog = new Animal(1,"Dog");

Animal Cat = Dog;

Animal Bird = Dog;

Console.WriteLine("Dog: " + Dog.Description);

Console.WriteLine("Cat: " + Cat.Description);

Console.WriteLine("Bird: " + Bird.Description);

// Now change Cat description to Cat

Cat.Description = "Cat";

// Print Again

Console.WriteLine("Changed Cat.Description to Cat");

Console.WriteLine("Dog: " + Dog.Description);

Console.WriteLine("Cat: " + Cat.Description);

Console.WriteLine("Bird: " + Bird.Description);

// Now change Bird description to Bird

Bird.Description = "Bird";

//Print again

Console.WriteLine("Changed Bird.Description to Bird");

Console.WriteLine("Cat: " + Cat.Description);

Console.WriteLine("Bird: " + Bird.Description);

Console.WriteLine("Dog: " + Dog.Description);

Console.ReadKey();

}

Now if we look into the code I defined the object Code of type Animal with new keyword and set Object Bird and Cat same as Dog. Now changed the Cat object and then Bird object and the result was:

So by changing any object here as far as none of the object defined as new keyword they all are actually referring to each other which proves that Object in C# copied by reference.









Friday 9 July 2010

Visual Studio 2010 Feature Part 1

Finally I started using Visual Studio 2010 and exploring. I found one interesting short cut to change the property SizeToContent of Window by just simply clicking to icon it changed from Fixed to Auto.

Auto Size:




Fixed Size: