2

I want to find the type of the generic T and compare that to check which interface it is, at run-time.

So, this works for finding the type of T at run-time :

Type interfaceName = typeof(T); // gives me the specific interface type

But when I try to check if it is equal to the type of an interface, I am not getting the expected response.

Type.GetType("IMyInterface"); //this returns null

How do I compare these two?

Servy
  • 202,030
  • 26
  • 332
  • 449
Setafire
  • 719
  • 2
  • 9
  • 21
  • 1
    Take a look at: http://stackoverflow.com/questions/4963160/how-to-determine-if-a-type-implements-an-interface-with-c-sharp-reflection – TryingToImprove Sep 09 '14 at 14:23
  • @TryingToImprove That's not what I was looking for. Besides, I didn't want to use Reflection in this part of my code. – Setafire Sep 09 '14 at 19:39

3 Answers3

2

If you want to use Type.GetType, you need to pass the assembly-qualified name.

However, it looks like you just want to check the name of an interface, so you can simply use

Type interfaceType = typeof(T);
string interfaceName = interfaceType.Name;

You can also simply check to see if typeof(T) == typeof(IMyInterface)

Alex
  • 7,639
  • 3
  • 45
  • 58
  • 1
    "simply check to see if typeof(T) == typeof(IMyInterface)" would be the correct answer all by itself. – Timothy Shields Sep 09 '14 at 14:28
  • The first solution would result in false positives if there were an interface with the same name elsewhere. The second solution wouldn't pass if the type is some type that implements or extends the interface. – Servy Sep 09 '14 at 14:38
  • @Servy Fair point on the first solution, it's a straightforward fix to the original post. But with regards to the second, the question states *"I want to find the type of the generic T and compare that to check **which interface it is**, at run-time."* - not which interface it implements or extends. – Alex Sep 09 '14 at 15:02
  • @AlexG Do you think he really means that or, do you think he didn't know the correct terminology to explain what he really wanted? – Servy Sep 09 '14 at 15:08
  • @Servy I wouldn't presume to know; if that is the case then the question can be closed as a duplicate of the one linked by TryingToImprove – Alex Sep 09 '14 at 15:32
  • @Servy : Alex read it right. I wanted to check the Interface type itself. – Setafire Sep 09 '14 at 15:49
  • @Servy Oh and by the way, this is she, not he. Just saying :) – Setafire Sep 09 '14 at 19:37
1

GetType method expects a fully qualified name. So you need either:

Type.GetType("YourNamespace.IMyInterface"); 

or if you have a reference to the assembly where IMyInterface is declared then just typeof(IMyInterface) will do the job.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

Maybe something like this:

typeof(T).Name == "IMyInterface"
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71