tags:

views:

84

answers:

5

Hi,

I have an interface like that:

 public interface IViewA : IViewB, IViewC
 {
    byte prop { get; set; }
 }

and I have a generic method like that:

public void OpenPopup<T>(WindowState state)
{
    if ((typeof(T) as IViewC)!=null)
    {
         //Process A
    }
    else
    {
        //Process B
    }

}

Although I send T as an interface which derives from IViewC, Process A is not being processed.

So how to learn at runtime via reflection whether an interface derives from other interface?

thanks

+2  A: 

Instead of typeof use isAssignableFrom.

JacobM
Please show sample code. I'm asking because I would think the answer needs both.
Steven Sudit
+4  A: 

Try the following

if ( typeof(IViewC).IsAssignableFrom(typeof(T)) { 
  ...
}
JaredPar
A: 
if ((typeof(T) as IViewC)!=null)

This is wrong. What you wrote tests whether the Type object returned by typeof(T) is an IViewC, which it obviously isn't.

You want:

if (typeof(IViewC).IsAssignableFrom(typeof(T))
JSBangs
I believe this is wrong as well. The "is" operator in C# can only be used on reference values. T is a generic type parameter.
JaredPar
@Jared, I updated to fix that.
JSBangs
+2  A: 

Try something like typeof(IViewC).IsAssignableFrom(typeof(T)).

Right now you're trying to treat typeof(T), which is a System.Type as IViewC, which will not work.

Nader Shirazie
+1  A: 

typeof(T) as IViewC is completely wrong. You are trying to cast from Type to IViewC, which will always fail, always resulting in null.

You want typeof(T).GetInterfaces(), and look through the returned list to see if your interface is in there.

Matt Greer
This would work, but not efficiently.
Steven Sudit