You can check this by seeing if the object's type is generic and if the corresponding generic template is the generic template that you are looking for. For example:
var type = obj.GetType();
bool isObjectADataMapper = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ObjectADataMapper<>);
Or, in a reusable way
bool IsInstanceOfGenericTypeClosingTemplate(object obj, Type genericTypeDefinition){
if(obj == null) throw new ArgumentNullException("obj");
if(genericTypeDefinition== null) throw new ArgumentNullException("genericTypeDefinition");
if(!genericTypeDefinition.IsGenericTypeDefinition) throw new ArgumentException("Must be a generic type definition.", "genericTypeDefinition");
Type type = obj.GetType();
return type.IsGenericType && type.GetGenericTypeDefinition() == genericTypeDefinition;
}
You could even take this further and see if the type is derived from the generic type definition in question. For example, consider that you have:
public class StringDataMapper : ObjectADataMapper<string>
{
// .... whatever
}
In this case the method I provided would fail. So you'd have to do something like
bool IsInstanceOfGenericTypeClosingTemplateOrSubclassThereof(object obj, Type genericTypeDefinition){
if(obj == null) throw new ArgumentNullException("obj");
if(genericTypeDefinition== null) throw new ArgumentNullException("genericTypeDefinition");
if(!genericTypeDefinition.IsGenericTypeDefinition) throw new ArgumentException("Must be a generic type definition.", "genericTypeDefinition");
Type type = obj.GetType();
while ( type != typeof(object) )
{
if(type.IsGenericType && type.GetGenericTypeDefinition() == genericTypeDefinition)
{
return true;
}
type = type.BaseType;
}
return false;
}