Question

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

Was it helpful?

Solution 2

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.

OTHER TIPS

A and B are different objects. They are of the same class, but not the same instance. Just like two people can both be people, but they are not the same person.

You are comparing the references of the two class instances. Since A and B reside at different memory locations their references are not equal. If you want to test class equality you will need to override the Equals() method. http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx

In your example if you were to test A == C you would see it return true since they both point to the same location in memory.

References types hold the address in memory. In your case A and B completely point to different addresses. However, C is pointing to the same address as A does since you assign A to C.

The output is correct as you are trying to compare the reference. Here A and B are different objects and hence they result in false on comparison.A, B all are at different memory locations and hence their references are not equal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top