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.