Given a structure like this:
class Parent { }
class Child : Parent { }
I have a method that takes a generic type with a constraint that the object is of type Child
static void doSomething<T>() where T : Child
{
if (typeof(T) == typeof(Parent))
{
/* ... */
}
else if (typeof(T) == typeof(Child))
{
/* ... */
}
}
the only problem is that, if I have:
class implementsParent : Parent { }
class implementsChild : Child { }
calling the generic method with a type of implementsParent won't work:
doSomething<implementsParent>(); // compile error
doSomething<implementsChild>(); // works fine
I'm trying to work around the fact that overloading a generic method doesn't take into account constraints.
What can I do here?
@Sander Rijken: Additional information.
I need to use the generic type to call an ORM framework method like so:
static void doSomething<T>() where T : Child
{
if (typeof(T) == typeof(Parent))
{
Parent obj = orm.GetObject<T>(criteria);
}
else if (typeof(T) == typeof(Child))
{
Child obj = orm.GetObject<T>(criteria);
}
}
having the constraint be where T : Parent causes the Child obj = orm.GetObject() to break because T cannot be converted to Type 'Child'
@Richard Hein:
Originally, I had 2 methods, each with a constraint to one of child/parent (in this case: XPObject and XPCustomObject from the DevExpress ORM - XPObject inherits from XPCustomObject).
The methods look like so:
static void removeBlank<T>(UnitOfWork uow) where T : XPObject
{
T blank = uow.GetObjectByKey<T>(0):
if (blank != null)
{
blank.Delete();
uow.CommitChanges();
}
}
XPCustomObject is used (in this case) to have PKs of type short (instead of the default int on XPObjects). So the only change is in the call to get the object:
static void removeBlankCustomObject<T>(UnitOfWork uow) where T : XPCustomObject
{
T blank = uow.GetObjectByKey<T>((short)0);
if (blank != null)
{
blank.Delete();
uow.CommitChanges();
}
}
The difference is minimal, so I want to merge the two methods together.