tags:

views:

139

answers:

3

Hello,

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

+2  A: 

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
so, I create a class inheriting of decimal..?
ibiza
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
how would that interface be defined more precisely please?
ibiza
+2  A: 

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
Thanks for the implicit operator hint, I found how to do it. Feel free to comment if it can be ameliorated
ibiza
+2  A: 

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; }
    }
ibiza
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