How can I check if an object is of a generic type?
For an argument, I have object
. I cannot change the signature of my function because I am extending the class of another class.
To give a concrete example, I have the following:
class Foo<T> : SomeBaseClass
{
public override MyFunction(object value)
{
// TODO: Figure out if value is an instance of Foo, though I don't care
// what type was associated with it.
}
}
Is there a way to make sure which value
is an instance of the type Foo
?
source to share
Ok if you want to check if this is enough Foo<something>
:
Type type = value.GetType();
if (!type.IsGenericType)
{
throw new ArgumentException("Not a generic type");
}
if (type.GetGenericTypeDefinition() != typeof(Foo<>))
{
throw new ArgumentException("Not the right generic type");
}
If you have to decide if this type derived from is going to be a Foo<T>
little trickier, because you don't necessarily know where it will be generic. For example, it could be:
class Bar : Foo<string>
or
class Baz<T> : Foo<T>
One alternative to ease the situation might be to introduce another non-generic class:
abstract class Foo : SomeBaseClass
class Foo<T> : Foo
Then you can simply do:
if (value is Foo)
Of course, this would also allow other types to get from Foo
. In many cases this won't be a problem, but it depends on your specific situation. You can also put any members who do not need to refer to T
on Foo
, so you can access them in such cases where you do not care T
.
source to share
You can try to call GetGenericTypeDefinition on value.GetType()
. This will basically give you either Foo<>
or an exception. To avoid the latter, check the flag IsGenericType
.
source to share
I don't think you can do this if you override the base class.
You could do something along these lines. The big drawback is that you lose compile-time type checking and omit it at runtime.
class Foo<T> : SomeBaseClass
{
public override MyFunction(object value)
{
if(value.GetType() != typeof(T))
{
// wrong type throw exception or similar
}
}
}
source to share