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?

+3


source to share


3 answers


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 accepts ShippingMethod

    and sets properties correctly
  • Create a static method on LocalizedShippingMethod

    that takes ShippingMethod

    and returns initializedLocalizedShippingMethod

  • Create an operator on LocalizedShippingMethod

    that converts fromShippingMethod

  • Create an extension method in ShippingMethod

    , call it ToLocalized()

    which returnsLocalizedShippingMethod

+2


source


What if you create an extension method for the ShippingMethod class?



0


source


The best way to do this is whichever way works best for you. If you are the person who has to maintain this code, what will make your life easier in the future?

Once you have answered this question, this is the best solution.

0


source







All Articles