Mazhar Khan
Mazhar Khan

Reputation: 404

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

Upvotes: 0

Views: 1173

Answers (5)

Soner Gönül
Soner Gönül

Reputation: 98840

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.

Upvotes: 1

lumberjack4
lumberjack4

Reputation: 2872

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.

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172578

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.

Upvotes: 0

Jason Whitted
Jason Whitted

Reputation: 4024

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.

Upvotes: 2

Dan Hunex
Dan Hunex

Reputation: 5318

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.

Upvotes: 0

Related Questions