Reputation: 5683
Is it possible (in c#
) to compare an open generic parameter e.g. T
in:
public void CompareMethod<T>() { ... }
with the type of an open generic interface (or class)?
Here is an example interface:
public interface IExample<T> { }
And then somehow inside the method compare them like this:
public void CompareMethod<T>()
{
if (typeof(IExample<>) == typeof(T))
{
//execute
}
}
The if
body won't execute when called the method like this:
CompareMethod<IExample<object>>();
It is important that I don't know in advance what closed types will be entered in the open generic parameter of the CompareMethod
.
Upvotes: 1
Views: 487
Reputation: 172646
You need to call GetGenericTypeDefinition()
on T
to be able to compare it with IExample<>
:
public void CompareMethod<T>()
{
if (typeof(T).IsGenericType &&
typeof(T).GetGenericTypeDefinition() == typeof(IExample<>)) {
{
//execute
}
}
Upvotes: 2