I have never done any extensive work with overloading operators, especially the implicit and explicit conversions.
However, I have several numeric parameters that are used frequently, so I am creating a struct as a wrapper around a numeric type to strongly type these parameters. Here's an example implementation:
public struct Parameter
{
private Byte _value;
public Byte Value { get { return _value; } }
public Parameter(Byte value)
{
_value = value;
}
// other methods (GetHashCode, Equals, ToString, etc)
public static implicit operator Byte(Parameter value)
{
return value._value;
}
public static implicit operator Parameter(Byte value)
{
return new Parameter(value);
}
public static explicit operator Int16(Parameter value)
{
return value._value;
}
public static explicit operator Parameter(Int16 value)
{
return new Parameter((Byte)value);
}
}
As i was experimenting with my test implementation to get a hang of the explicit and implicit operators, I tried to explicitly cast a Int64
to my Parameter
type and to my surprised it did not throw an exception, and even more surprising, it just truncated the number and moved on. I tried excluding the custom explicit operator and it still behaved the same.
public void TestCast()
{
try
{
var i = 12000000146;
var p = (Parameter)i;
var d = (Double)p;
Console.WriteLine(i); //Writes 12000000146
Console.WriteLine(p); //Writes 146
Console.WriteLine(d); //Writes 146
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); //Code not reached
}
}
So I repeated my experiment with a plain Byte
in place of my struct and has the same exact behavior, so obviously this is expected behavior, but I thought an explicit cast that results in a lose of data would throw an exception.