I have following C# code in .Net 4.0. It requires a type casting of IBusiness to IRetailBusiness.
//Type checking
if (bus is IRetailBusiness)
{
//Typ
Basically, if I understood you right, you want to avoid the type casting.
You can accomplish that simply by changing the constructor signature from:
public RetailInvestmentReturn(IRetailBusiness retail) {...}
public IntellectualRightsInvestmentReturn(IIntellectualRights intellectual) {...}
to:
public RetailInvestmentReturn(IBusiness retail) {...}
public IntellectualRightsInvestmentReturn(IBusiness intellectual) {...}
If that is not an option due to design constraints, then you can try to use the strategy pattern. That would still need a type cast, but you would get rid of the terrifying "ifs" and "elses", that, I believe, is your real question, right? In order to do that you need to:
In code, that would look something like this:
(Create,...)
Dictionary> dict = new Dictionary>
{
{typeof (BookShop), business => new RetailInvestmentReturn((IRetailBusiness) business)},
{typeof (AudioCDShop), business => new IntellectualRightsInvestmentReturn((IIntellectualRights) business)}
};
(Use it!)
// try this:
foreach (IBusiness bus in allMyProfitableBusiness)
{
investmentReturns.Add(dict[bus.GetType()](bus));
}