1

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.

Rand Random
  • 7,300
  • 10
  • 40
  • 88
Deva Raja
  • 69
  • 3

2 Answers2

5

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.

JHBonarius
  • 10,824
  • 3
  • 22
  • 41
0

Thank you for your answers but I think I found the solution. Every object of the class Type, which represents another type(string, int etc) must be unique, that is there cannot be two objects of the class Type representing the same type in the same application. So typeof(string) creates one Type object representing string, and then s.GetType() does not create another Type object representing string, but refers to the first object.

"For any type, there is only one instance of Type per application domain."

"A Type object that represents a type is unique; that is, two Type object references refer to the same object if and only if they represent the same type."

https://learn.microsoft.com/en-us/dotnet/api/system.type?view=netstandard-1.6

Deva Raja
  • 69
  • 3