0

I have this code in an if statements which evaluates to false and I don't have any clue why

&& (typeof(TResponse).Equals(typeof(MediatorResponse)))

used Equals as I intend to compare by reference

I tried to put them in watch and this is my clue

click to see

typeof(TResponse) seems to be a MediatorResponse'1 while typeof(MediatorResponse) seems to be a MediatorResponse are these 2 still of the same type?

Why does visual studio put 1 on the other?

Fred
  • 3,365
  • 4
  • 36
  • 57
  • 1
    They are clearly different on the screenshot. Check the `Name` of the types – Renat Mar 04 '20 at 09:59
  • I see the difference. my question would be why. – Andrew Mcmellan Mar 04 '20 at 10:00
  • Isn't TResponse Generic type? – jasonvuriker Mar 04 '20 at 10:01
  • `TResponse` is of type `MediatorResponse`, whereas the other one is not generic, most likely the base class for the generic one. `\`1` is the way the type objects will say ``, if it is `\`2`, it will have 2 generic arguments. – Lasse V. Karlsen Mar 04 '20 at 10:03
  • Looks like there is a base class and an inherited class. So you can cast a base class to an inherited class which looks like what happened in this case. So yes they are equivalent in this case. – jdweng Mar 04 '20 at 10:04
  • In your line of code it is not quite clear what TResponse and MediatorResponse are. It looks like you are just comparing type of one class with the type of another class (which by default is not the same). Instead you should get the type of a referenced objeect and compare it with the type of another referenced object. Except of the case your example is just a copy and paste error. – rekcul Mar 04 '20 at 10:05
  • I dont think that the proposed link will help to solve the issue. The code should look like `myResponseObj.GetType().Equals(typeof(MediatorResponse))` instead of `typeof(TResponse).Equals(typeof(MediatorResponse)`. Comparing typeof(class1) with typeof(class2) will never be true. – rekcul Mar 04 '20 at 10:24

1 Answers1

1

C# allows you to have different types with the same name if one or more and generic, and if the generic types have a different number of generic arguments. For example, the following are all different types:

class Foo{}
class Foo<T>{}
class Foo<T1, T2>{}

The backtick character followed by a number is used on generic types to generate a unique name, and indicate the number of generic arguments the type has. So in the above example the names would be:

class Foo{}            // Name is Foo
class Foo<T>{}         // Name is Foo`1
class Foo<T1, T2>{}    // Name is Foo`2
Sean
  • 60,939
  • 11
  • 97
  • 136