I have never done extensive work with overload operators, especially with implicit and explicit conversions.
However, I have several numerical parameters that are used frequently, so I create the structure as a wrapper around the numerical type in order to type these parameters strongly. Here is 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); } }
Since I was experimenting with my test implementation to get the hang of explicit and implicit statements, I tried to explicitly use the Int64 type for my Parameter , and to my surprise, he didn't throw an exception and even more surprisingly, he simply truncated the number and moved on. I tried to exclude the user explicit operator, and it still behaved the same way.
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 simple Byte instead of my structure and had the exact same behavior, so it is obvious that this is the expected behavior, but I thought that an explicit cast leading to data loss would throw an exception.
psubsee2003
source share