If you're in an environment where you don't care too much about performance then reflection can be a solution for you. However, I'd recommend not using reflection and instead having Entity<T>
inherit from a non-generic type of Entity
or IEntity
(see Silvermind's answer).
For reflection these extension methods should allow you to check against typeof(Entity<>)
(the optional boolean argument defaults to checking base types too):
static bool IsInstanceOfGenericType(this object item, Type @type, bool includeBaseTypes = true) {
return item.GetType().IsBasedOnGenericType(@type, includeBaseTypes);
}
static bool IsBasedOnGenericType(this Type t, Type @type, bool includeBaseTypes = true) {
return (t.IsGenericType && t.GetGenericTypeDefinition() == @type)
|| includeBaseTypes
&& (t.GetInterfaces().Any(i => IsBasedOnGenericType(i, @type))
|| (t.BaseType != null ? IsBasedOnGenericType(t.BaseType, @type) : false));
}
The IsInstanceOfGenericType
method can be used as so:
class InheritingClass : Entity<string> { }
class Entity<T> : IEntity<T> { }
interface IEntity<T> { }
var item = new InheritingClass();
var item2 = new Entity<string>();
var item3 = new Entity<string>();
var item4 = new List<string>();
var item5 = new InheritingClass();
Console.WriteLine( "item: " + item.IsInstanceOfGenericType(typeof(Entity<>)) );
Console.WriteLine( "item2: " + item2.IsInstanceOfGenericType(typeof(Entity<>)) );
Console.WriteLine( "item3: " + item3.IsInstanceOfGenericType(typeof(IEntity<>)) );
Console.WriteLine( "item4: " + item4.IsInstanceOfGenericType(typeof(IEntity<>)) );
Console.WriteLine( "item5: " + item5.IsInstanceOfGenericType(typeof(Entity<>), false) );
item: True
item2: True
item3: True
item4: False
item5: False