Is there a good, generic, way to do the following without resorting to a second method or lots of casts – I want to keep the API as light as possible and it seems ok to me OO-wise:
class Foo
{
public T Bar<T>() where T: IAlpha
{
/* blahblahblah */
}
public T Bar<T>() where T: IBeta
{
/* blahblahblah */
}
}
interface IAlpha
{
string x {set;}
}
interface IBeta
{
string y {set;}
}
thanks
You can’t overload a method by return value only (generic or not). Additionally, it would be impossible to resolve calls to
Bar, since an object could implement bothIAlphaandIBeta, so this is not possible using overloading.The below will also not work, because the methods only differ by return type
Unfortunately, your best solution will be to use a less generic solution. The command pattern might serve you well here.
Another way of implementing Bar which allows you to call it without explicitly declaring the type (in your angled brackets) is to use an out parameter. I’d avoid it, however, since out parameters in 100% managed usually stink of bad design.
I excluded
Command,AlphaCreationCommand,BetaCreationCommand, andTypeNotSupportedException. Their implementation should be fairly self explanatory.Alternately, you can use Func instead of Commands, but this forces you to implement all of your instantiation code in
Foowhich can get out of hand as your code base grows.