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

  • Thread starter Thread starter Keith Patrick
  • Start date Start date
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>.
 
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

--
 
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
 
Back
Top