1

I have the following sample.

namespace sample
{
    public class Customer
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Customer C1 = new Customer();
            C1.ID = 100;
            C1.Name = "Mary";

            Customer C2 = C1;

            C2.Name = "Sandra";

            Console.WriteLine("C1.Name ={0} && C2.Name = {1}", C1.Name, C2.Name);

        }
    }
}

Why does the value of C1 changes when I assign a new value to C2. So in the end I get the following result: C1.Name =Sandra && C2.Name = Sandra

CsharpLover
  • 47
  • 2
  • 6

3 Answers3

2

Because they're both references to the same object!

The opposite would be:

        Customer C1 = new Customer();
        C1.ID = 100;
        C1.Name = "Mary";

        // New instance stored on C2 reference
        // so now both are different references to also
        // different objects
        Customer C2 = new Customer(); 

        C2.Name = "Sandra";
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
0

C1 and C2 are both references to the same instance of Customer.

C2.Name = "Sandra"; changes the name of that customer via the reference C2

You could change Customer to a value-type by making it a struct rather than a class, or use the syntax Customer C2 = new Customer(); to create a new Customer object.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

The phenomenon you observe is called aliasing. You have created references C1 and C2. However, these do not refer to different objects, but one object, namely the one created by the constructor call new Customer(). Apparently you expect the statement

Customer C2 = C1;

to create a new customer object which then gets assigned the same values as C1. This is not the case - you create a new reference named C2 which referes to the same object as C1.

Codor
  • 17,447
  • 9
  • 29
  • 56