2

let's say I have a list of decimals :

List<decimal> values;

and 2 function to display a decimal :

string DisplayPct(decimal pct)
{
   return pct.ToString("0.00 %");
}

string DisplayValue(decimal val)
{
   return val.ToString("0.00");
}

What would be the best mechanism to implement so I could know which function to call depending on the value?

I would have liked to have for instance typedefs in C#. That way, I could have declared a type Percent and a type Decimal that would both represent decimal values, but then I could know how to display the value based on its type.

Any equivalent in C# ?

Thanks

Bruno
  • 4,685
  • 7
  • 54
  • 105
  • 1
    Just for your information: Depending on the locale the delimiter could be a comma instead of a dot. – some Oct 03 '10 at 23:53

3 Answers3

3

Here are my classes :

    public class Percent
    {
        public decimal value;
        public Percent(decimal d) { value = d; }
        public static implicit operator Percent(decimal d) { return new Percent(d); }
        public static implicit operator decimal(Percent p) { return p.value; }
    }
    public class DecimalPrecise
    {
        public decimal value;
        public DecimalPrecise(decimal d) { value = d; }
        public static implicit operator DecimalPrecise(decimal d) { return new DecimalPrecise(d); }
        public static implicit operator decimal(DecimalPrecise d) { return d.value; }
    }
Bruno
  • 4,685
  • 7
  • 54
  • 105
  • Just override the ToString()'s and you're good to go. I forgot that it decimals shouldn't be wrapped in structs, I'll edit my answer. – Jonn Oct 04 '10 at 01:16
2

It sounds like you want two classes: a decimal and a percent. Each one will have a ToString that prints appropriately. If they both have the same interface, you can have a collection of both in a List using that common interface.

JoshD
  • 12,490
  • 3
  • 42
  • 53
  • so, I create a class inheriting of decimal..? – Bruno Oct 03 '10 at 23:57
  • Not quite. Your list should be of type `value` where value is the common interface. Then create two classes that each inherit from `value`: decimal and percent. – JoshD Oct 04 '10 at 00:00
  • how would that interface be defined more precisely please? – Bruno Oct 04 '10 at 00:02
2

Wrap percent in a class. A bit of work on your part. Just make sure to define the implicit operator to capture decimals, and some of the other operations and ToString as you require.

Jonn
  • 4,599
  • 9
  • 48
  • 68
  • Thanks for the implicit operator hint, I found how to do it. Feel free to comment if it can be ameliorated – Bruno Oct 04 '10 at 00:52