tags:

views:

1080

answers:

4

I have the following classes

public interface InterfaceBase
{
}

public class ImplementA:InterfaceBase
{
}

public class ImplementB:InterfaceBase
{
}

public void TestImplementType<T>(T obj) where T: InterfaceBase
{
}

How to infer what the T is whether ImplementA or ImplementB? I tried to use

typeof(T) is ImplementA

but this expression is always evaluated to false.

Edit: And how am I going to cast obj to ImplementA or ImplementB?

+3  A: 

obj is ImplementA

Toby
Again, that doesn't say that T derives from ImplementA - it only talks about the particular value of obj. TestImplementType<InterfaceBase>(new ImplementA()) will pass when (according to the actual question) it shouldn't.
Jon Skeet
A: 

How about:

 if(obj.GetType().Equals(typeof(ImplementA)))
 {
   // ...
 }
Andrew Stapleton
That's not the same thing. For instance, you could call:TetstImplementType<object>(new ImplementA())
Jon Skeet
Actually, the compiler won't let you instantiate TestImplementType<object>.The type System.Object does not implement InterfaceBase.
Andrew Stapleton
Oops, hadn't seen the constraint. However, the root point is sound - typeof(T) isn't the same as obj.GetType(). You could certainly write TestImplementType<InterfaceBase>(new ImplementA()). Furthermore, this example doesn't cope with classes derived from ImplementA.
Jon Skeet
+2  A: 

typeof(T) returns the Type of T - and System.Type doesn't implement ImplementA. What you want is:

if (typeof(ImplementA).IsAssignableFrom(typeof(T))
{
}
Jon Skeet
+4  A: 

Strictly, you should avoid too much specialization within generics. It would be cleaner to put any specialized logic in a member on the interface, so that any implementation can do it differently. However, there are a number of ways:

You can test "obj" (assuming it is non-null)

    bool testObj = obj is ImplementA;

You can test T for being typeof(ImplementA):

    bool testEq = typeof(T) == typeof(ImplementA);

Likewise you can test it for being ImplementA or a subclass:

    bool testAssign = typeof(ImplementA).IsAssignableFrom(typeof(T));
Marc Gravell