December 13, 2010 by Christoff Truter C#
Within C# (among other languages) we've got the ability to overload implicit / explicit
conversion operators.
Just to get everyone up to speed, an implicit conversion refers to an action that happens automatically
(the compiler infers - decides what the appropriate type is to use) e.g.
Decimal d = 10.9M;
int i = (int)d; // d being the decimal value from the preceding snippet
struct Pound { public Pound(float value) { this._Value = value; } private float _Value; public float Value { get { return _Value; } } public static implicit operator Pound(float value) { return new Pound(value); } public static explicit operator Pound(Kilogram value) { return new Pound(value.Value * 2.20462262f); } } struct Kilogram { public Kilogram(float value) { this._Value = value; } private float _Value; public float Value { get { return _Value; } } public static implicit operator Kilogram(float value) { return new Kilogram(value); } public static explicit operator Kilogram(Pound value) { return new Kilogram(value.Value * 0.45359237f); } }
Pound p = 100; // public static implicit operator Pound(float value)
Kilogram kg = (Kilogram)p; // public static explicit operator Kilogram(Pound value)