polymorphism, inheritance in c# - base class calling overridden method?
- by Andrew Johns
This code doesn't work, but hopefully you'll get what I'm trying to achieve here. I've got a Money class, which I've taken from http://www.noticeablydifferent.com/CodeSamples/Money.aspx, and extended it a little to include currency conversion.
The implementation for the actual conversion rate could be different in each project, so I decided to move the actual method for retrieving a conversion rate (GetCurrencyConversionRate) into a derived class, but the ConvertTo method contains code that would work for any implementation assuming the derived class has overriden GetCurrencyConversionRate so it made sense to me to keep it in the parent class? So what I'm trying to do is get an instance of SubMoney, and be able to call the .ConvertTo() method, which would in turn use the overriden GetCurrencyConversionRate, and return a new instance of SubMoney.
The problem is, I'm not really understanding some concepts of polymorphism and inheritance yet, so not quite sure what I'm trying to do is even possible in the way I think it is, as what is currently happening is that I end up with an Exception where it has used the base GetCurrencyConversionRate method instead of the derived one. Something tells me I need to move the ConvertTo method down to the derived class, but this seems like I'll be duplicating code in multiple implementations, so surely there's a better way?
public class Money
{
public CurrencyConversionRate
{
get
{
return GetCurrencyConversionRate(_regionInfo.ISOCurrencySymbol);
}
}
public static decimal GetCurrencyConversionRate(string isoCurrencySymbol)
{
throw new Exception("Must override this method if you wish to use it.");
}
public Money ConvertTo(string cultureName)
{
// convert to base USD first by dividing current amount by it's exchange rate.
Money someMoney = this;
decimal conversionRate = this.CurrencyConversionRate;
decimal convertedUSDAmount = Money.Divide(someMoney, conversionRate).Amount;
// now convert to new currency
CultureInfo cultureInfo = new CultureInfo(cultureName);
RegionInfo regionInfo = new RegionInfo(cultureInfo.LCID);
conversionRate = GetCurrencyConversionRate(regionInfo.ISOCurrencySymbol);
decimal convertedAmount = convertedUSDAmount * conversionRate;
Money convertedMoney = new Money(convertedAmount, cultureName);
return convertedMoney;
}
}
public class SubMoney
{
public SubMoney(decimal amount, string cultureName) : base(amount, cultureName) {}
public static new decimal GetCurrencyConversionRate(string isoCurrencySymbol)
{
// This would get the conversion rate from some web or database source
decimal result = new Decimal(2);
return result;
}
}