Class inheritance and adding an additional property
I have a class in one application - which I cannot change (legacy) - inside an assembly (DLL file):
public class ShippingMethod
{
public string ShipMethodCode { get; set; }
public string ShipMethodName { get; set; }
public decimal ShippingCost { get; set; }
public List<ShippingMethod> GetAllShippingMethods()
{
......
}
}
I have a second application that references this assembly (DLL file) and needs to populate the dropdown with all Shipping Methods. Example: "UPS - $ 3.25"
The problem is that it has to use the correct format for different currencies. Example: $ 3.25 or β¬ 3.25 depending on the CountryID setting.
I wrote a function String DisplayMoney(Decimal Amount, Integer CountryID)
that will return the correct sum format.
Now I need to apply this function to each shipping method and save it to a new list. What's the best way to do this?
I can create another class called LocalizedShippingMethods like this:
public class LocalizedShippingMethod
{
public ShippingMethod ShipMethod { get; set; }
public string LocalizedShippingCost { get; set; }
}
Is this the best way to achieve this? Is there a better way to do this using inheritance? And if I use inheritance, how do I get the values ββfrom the first list in the NEW LIST?
source to share
This is a really good way to do it. You can use a fairly quick Linq query to pull the old one List
into the new one:
List<LocalizedShippingMethod> Translate(List<ShippingMethod> oldList)
{
return oldList.Select(a => new LocalizedShippingMethod
{
// Initialize properties according to however you translate them
}).ToList();
}
Also, to make it more orderly and obvious, you can do any of the following to help translate:
- Create a constructor for
LocalizedShippingMethod
that acceptsShippingMethod
and sets properties correctly - Create a static method on
LocalizedShippingMethod
that takesShippingMethod
and returns initializedLocalizedShippingMethod
- Create an operator on
LocalizedShippingMethod
that converts fromShippingMethod
- Create an extension method in
ShippingMethod
, call itToLocalized()
which returnsLocalizedShippingMethod
source to share