For the sake of argument, I have an object. I can’t modify the signature of my function because I am extending someone else’s 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 that value is some instance of a Foo type?
Well, if you want to check whether it’s exactly a
Foo<something>it’s fairly easy:If you need to decide whether it’s some type derived from
Foo<T>it’s slightly harder – because you don’t necessarily know where it’ll be generic. For example, it could be:or
One alternative to make things easier might be to introduce another non-generic class:
Then you can just do:
Of course that would also allow for other types deriving from
Foo. In many cases that wouldn’t really be a problem, but it depends on your exact situation. You could also put any members which don’t need to refer toTintoFoo, so you could access them in cases like this where you don’t care aboutT.