'is' keyword and generics (ignoring the type parameter)

K

Keith Patrick

If I have a class: BaseObject<T>, is there some way to generically say:
if (myObj is BaseObject) without the type parameter? Using
BaseObject<Object> won't work because the runtime insists that the derived
type literally be BaseObject<Object> and not
BaseObject<anyderivativeofObject>.
 
F

Frans Bouma [C# MVP]

Keith said:
If I have a class: BaseObject<T>, is there some way to generically
say: if (myObj is BaseObject) without the type parameter? Using
BaseObject<Object> won't work because the runtime insists that the
derived type literally be BaseObject<Object> and not
BaseObject<anyderivativeofObject>.

That's indeed not possible. If you want to do that, implement
interfaces (non-generic) on the BaseObject<T>. For example internal
interfaces which are known internally in your framework. You then can
use 'is' with the internal interface to test if the object supports a
given interface you need to use to interact with the baseobject<T>.

FB

--
 
G

Guest

if (myObj is BaseObject) without the type parameter?

Not with the is operator, only with Reflection.

static bool IsBaseObjectOfSomething(object o)
{
return o != null && o.GetType().IsGenericType &&
o.GetType().GetGenericTypeDefinition() == typeof(BaseObject<>);
}

But I'm curious what you would do with that information. In practice to do
anything useful with the object you probably need a non-generic base class or
interface like Frans suggested.


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top