2

I am thinking what I want to do is impossible but thought I would ask anyway. I am thinking of implementing some kind of custom conversion between different metric measurements - such as converting inches to metres and other units.

I am thinking base class called Unit as follows. NOTE: I have not put in any fields to hold the number of units eg 2 metres, 5 inches and so on:

public abstract class Unit {
    protected string _name;
    public Unit(string name)
    {
        _name = name;
    }
}

Then subclasses of Unit for Metre and Inch:

public class Metre : Unit {
    public Metre() : base("Metre")
    {
    }
}

public class Inch : Unit {
    public Metre() : base("Inch")
    {
    }
}

I would like to have a class that could handle conversion of these units between one another. Something like:

public static class UnitConvertor
{
    public Unit Convert(Unit from, Type to) : where Type extends/inherits from Unit
    {
        // do the conversion
        return the instance of Type to;
    }
}

Any thoughts?

Andez
  • 5,588
  • 20
  • 75
  • 116
  • 4
    `Convert(T from, T to) where T : Unit` would probably be the appropriate solution. – vcsjones Jan 17 '12 at 22:14
  • vcsjones - would you mean Convert(EngineeringUnit from, T to) where T : Unit? You would need to pass an instance of T - i.e. a new Meter as second parameter - ideally you don't want the caller to instantiate the return type. You would just want to say, here is a Inch instance, give me the Meter equivalent. – Andez Jan 17 '12 at 22:30
  • Unless there is a viable generics solution for this guys. I've looked and looked but not seen anything that would fit. Feel free to share any info I might have missed. – Andez Jan 17 '12 at 22:33

1 Answers1

5

If the units are all known ahead of time you could use an implicit conversion operator:

public class Metre : Unit 
{
    public Metre() : base("Metre")
    {
    }

    public static implicit operator Inch(Metre m)  
    { 
        return new Inch(39.37 * m.Value);
    }
}
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • Yes - and you have to update the individual classes if you want to add a new unit, not saying it's pretty either ;-) – BrokenGlass Jan 17 '12 at 22:18
  • Yes, there will be lots of units. I put 2 on example for discussion, but kind of like the example. – Andez Jan 17 '12 at 22:23
  • A "workaround" could be that all units are convertible to meter, and meter would be convertible to all other units - kludgy but could use that in the converter class to get around the N*N conversions. – BrokenGlass Jan 17 '12 at 22:29