Reputation: 6888
Supposing I have a method:
public void DoStuff<T>() where T : IMyInterface {
...
}
And elsewhere in a different method I want to call
public void OtherMethod<T>() where T : class {
...
if (typeof(T) is IMyInterface) // have ascertained that T is IMyInterface
DoStuff<T>();
}
Is there some way I can cast T as having my interface?
DoStuff<(IMyInterface)T>
and other similar variations wouldn't work for me.
Edit: thanks for pointing out that typeof(T) is IMyInterface
is the wrong way to check for the interface and should instead be called on an actual instance of T.
Edit2: I found that (IMyInterface).IsAssignableFrom(typeof(T))
worked in checking for the interface.
Upvotes: 2
Views: 1686
Reputation: 152521
This line is wrong:
if (typeof(T) is IMyInterface) // have ascertained that T is IMyInterface
DoStuff<T>();
typeof(T)
returns a Type
, which will never be a IMyinterface
. If you have an instance of T, you can use
if (instanceOfT is IMyInterface) // have ascertained that T is IMyInterface
DoStuff<T>();
or
if (instanceOfT is IMyInterface) // have ascertained that T is IMyInterface
DoStuff<IMyInterface>();
Otherwise you could use reflection as Tim S suggests.
Upvotes: 1
Reputation: 708
You can use the same syntax to inherit from multiple interfaces:
public void OtherMethod<T>() where T : class, IMyInterface {
...
}
Upvotes: 2
Reputation: 56536
I think the most straightforward way to do that is with reflection. E.g.
public void OtherMethod<T>() where T : class {
if (typeof(IMyInterface).IsAssignableFrom(typeof(T))) {
MethodInfo method = this.GetType().GetMethod("DoStuff");
MethodInfo generic = method.MakeGenericMethod(typeof(T));
generic.Invoke(this, null);
}
}
Upvotes: 3