Search code examples
c#.netoopclassreference-type

Reference Type comparison in C#


I am trying to understand below problem. I want to know why B == A and C == B are false in the following program.

using System;

namespace Mk
{
    public class Class1
    {
        public int i = 10;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class1 A = new Class1();
            Class1 B = new Class1();
            Class1 C = A;

            Console.WriteLine(B == A);
            Console.WriteLine(C == B);
        }
    }
}

Output:

False
False


Solution

  • In .NET, classes are reference types. Reference types has two thing. Object and a reference to object.

    In your case, A is a reference to the ObjectA, B is a reference to the ObjectB.

    When you define Class1 C = A;

    • First, you create two thing. An object called ObjectC and a reference to the object called C.
    • Then you copy reference of A to reference of C. Now, A and C is reference to the same object.

    When you use == with reference objects, if they reference to the same objets, it returns true, otherwise return false.

    In your case, that's why B == A and C == B returns false, but if you tried with A == C, it returns true.