You have a good start, but like Jon said, it's currently not type-safe; the converter has no error-checking to ensure the decimal it gets is a Celsius value.
So, to take this further, I would start introducing struct types that take the numerical value and apply it to a unit of measure. In the Patterns of Enterprise Architecture (aka the Gang of Four design patterns), this is called the "Money" pattern after the most common usage, to denote an amount of a type of currency. The pattern holds for any numeric amount that requires a unit of measure to be meaningful.
Example:
public enum TemperatureScale
{
Celsius,
Fahrenheit,
Kelvin
}
public struct Temperature
{
decimal Degrees {get; private set;}
TemperatureScale Scale {get; private set;}
public Temperature(decimal degrees, TemperatureScale scale)
{
Degrees = degrees;
Scale = scale;
}
public Temperature(Temperature toCopy)
{
Degrees = toCopy.Degrees;
Scale = toCopy.Scale;
}
}
Now, you have a simple type that you can use to enforce that the conversions you are making take a Temperature that is of the proper scale, and return a result Temperature known to be in the other scale.
Your Funcs will need an extra line to check that the input matches the output; you can continue to use lambdas, or you can take it one step further with a simple Strategy pattern:
public interface ITemperatureConverter
{
public Temperature Convert(Temperature input);
}
public class FahrenheitToCelsius:ITemperatureConverter
{
public Temperature Convert(Temperature input)
{
if (input.Scale != TemperatureScale.Fahrenheit)
throw new ArgumentException("Input scale is not Fahrenheit");
return new Temperature(input.Degrees * 5m / 9m - 32, TemperatureScale.Celsius);
}
}
//Implement other conversion methods as ITemperatureConverters
public class TemperatureConverter
{
public Dictionary<Tuple<TemperatureScale, TemperatureScale>, ITemperatureConverter> converters =
new Dictionary<Tuple<TemperatureScale, TemperatureScale>, ITemperatureConverter>
{
{Tuple.Create<TemperatureScale.Fahrenheit, TemperatureScale.Celcius>,
new FahrenheitToCelsius()},
{Tuple.Create<TemperatureScale.Celsius, TemperatureScale.Fahrenheit>,
new CelsiusToFahrenheit()},
...
}
public Temperature Convert(Temperature input, TemperatureScale toScale)
{
if(!converters.ContainsKey(Tuple.Create(input.Scale, toScale))
throw new InvalidOperationException("No converter available for this conversion");
return converters[Tuple.Create(input.Scale, toScale)].Convert(input);
}
}
Because these types of conversions are two-way, you may consider setting up the interface to handle both ways, with a "ConvertBack" method or similar that will take a Temperature in the Celsius scale and convert to Fahrenheit. That reduces your class count. Then, instead of class instances, your dictionary values could be pointers to methods on instances of the converters. This increases the complexity somewhat of setting up the main TemperatureConverter strategy-picker, but reduces the number of conversion strategy classes you must define.
Also notice that the error-checking is done at runtime when you are actually trying to make the conversion, requiring this code to be tested thoroughly in all usages to ensure it's always correct. To avoid this, you can derive the base Temperature class to produce CelsiusTemperature and FahrenheitTemperature structs, which would simply define their Scale as a constant value. Then, the ITemperatureConverter could be made generic to two types, both Temperatures, giving you compile-time checking that you are specifying the conversion you think you are. the TemperatureConverter can also be made to dynamically find ITemperatureConverters, determine the types they will convert between, and automagically set up the dictionary of converters so you never have to worry about adding new ones. This comes at the cost of increased Temperature-based class count; you'll need four domain classes (a base and three derived classes) instead of one. It will also slow the creation of a TemperatureConverter class as the code to reflectively build the converter dictionary will use quite a bit of reflection.
You could also change the enums for the units of measure to become "marker classes"; empty classes that have no meaning other than that they are of that class and derive from other classes. You could then define a full hierarchy of "UnitOfMeasure" classes that represent the various units of measure, and can be used as generic type arguments and constraints; ITemperatureConverter could be generic to two types, both of which are constrained to be TemperatureScale classes, and a CelsiusFahrenheitConverter implementation would close the generic interface to the types CelsiusDegrees and FahrenheitDegrees both derived from TemperatureScale. That allows you to expose the units of measure themselves as constraints of a conversion, in turn allowing conversions between types of units of measure (certain units of certain materials have known conversions; 1 British Imperial Pint of water weighs 1.25 pounds).
All of these are design decisions that will simplify one type of change to this design, but at some cost (either making something else harder to do or decreasing algorithm performance). It's up to you to decide what's really "easy" for you, in the context of the overall application and coding environment you work in.
EDIT: The usage you want, from your edit, is extremely easy for temperature. However, if you want a generic UnitConverter that can work with any UnitofMeasure, then you no longer want Enums to represent your units of measure, because Enums can't have a custom inheritance hierarchy (they derive directly from System.Enum).
You can specify that the default constructor can accept any Enum, but then you have to ensure that the Enum is one of the types that is a unit of measure, otherwise you could pass in a DialogResult value and the converter would freak out at runtime.
Instead, if you want one UnitConverter that can convert to any UnitOfMeasure given lambdas for other units of measure, I would specify the units of measure as "marker classes"; small stateless "tokens" that only have meaning in that they are their own type and derive from their parents:
//The only functionality any UnitOfMeasure needs is to be semantically equatable
//with any other reference to the same type.
public abstract class UnitOfMeasure:IEquatable<UnitOfMeasure>
{
public override bool Equals(UnitOfMeasure other)
{
return this.ReferenceEquals(other)
|| this.GetType().Name == other.GetType().Name;
}
public override bool Equals(Object other)
{
return other is UnitOfMeasure && this.Equals(other as UnitOfMeasure);
}
public override operator ==(Object other) {return this.Equals(other);}
public override operator !=(Object other) {return this.Equals(other) == false;}
}
public abstract class Temperature:UnitOfMeasure {
public static CelsiusTemperature Celsius {get{return new CelsiusTemperature();}}
public static FahrenheitTemperature Fahrenheit {get{return new CelsiusTemperature();}}
public static KelvinTemperature Kelvin {get{return new CelsiusTemperature();}}
}
public class CelsiusTemperature:Temperature{}
public class FahrenheitTemperature :Temperature{}
public class KelvinTemperature :Temperature{}
...
public class UnitConverter
{
public UnitOfMeasure BaseUnit {get; private set;}
public UnitConverter(UnitOfMeasure baseUnit) {BaseUnit = baseUnit;}
private readonly Dictionary<UnitOfMeasure, Func<decimal, decimal>> converters
= new Dictionary<UnitOfMeasure, Func<decimal, decimal>>();
public void AddConverter(UnitOfMeasure measure, Func<decimal, decimal> conversion)
{ converters.Add(measure, conversion); }
public void Convert(UnitOfMeasure measure, decimal input)
{ return converters[measure](input); }
}
You can put in error-checking (check that the input unit has a conversion specified, check that a conversion being added is for a UOM with the same parent as the base type, etc etc) as you see fit. You can also derive UnitConverter to create TemperatureConverter, allowing you to add static, compile-time type checks and avoiding the run-time checks that UnitConverter would have to use.