Home > Mobile >  Value or referential comparison?
Value or referential comparison?

Time:07-17

In this website I read the following code which I think is wrong:

string s = "Geeks";
 
Type a1 = typeof(string);
 
Type a2 = s.GetType();
 
Console.WriteLine(a1 == a2);

//output: True

Now, please correct me if I am wrong because I am new in C#.

  1. "Geeks" is a string object.
  2. typeof(string) returns a Type object.
  3. s.GetType() returns a Type object.
  4. a1 and a2 are reference type variables of datatype Type.

So a1==a2 should be a referential comparison and should return false since there are two different Type objects.

CodePudding user response:

Although that is true for general reference types, one can overload the equality operator to compare the contents instead.

System.Type has such an overload

Furthermore, like System.Object.GetType states:

For two objects x and y that have identical runtime types, Object.ReferenceEquals(x.GetType(),y.GetType()) returns true.

CodePudding user response:

String type just implements custom equality comparison operators. Any class can do that and overrides "==". (and also other equality operators). so as you can see it behaves "like value-type".

This question has already been answered here and here. have a look for more information

  •  Tags:  
  • c#
  • Related