[Mono-list] Conversion notes

Derek Holden dholden@draper.com
Tue, 17 Jul 2001 08:36:50 -0400


Here are notes and thoughts while working on System.Convert and implementing
IConvertible on some of the core data types. There are decisions that should
be made by the library lead and some notes on spec/ms/sdk doc discrepencies.
These aren't immediate threats, I just want to get these notes on record.

System.Convert is pretty much just a class w/ a bunch of static To<Type>
methods to do data type conversions. Convert.ToDouble(float),
Convert.ToBoolean(byte), etc. System.IConvertible is an interface that
defines all possible To<Types>, so a class that implements it would have to
define its conversion to all possible other types.

There are two obvious ways those two could work together. System.Convert can
just be a wrapper for the implemented IConvertible functions or vice versa.
Specifically,

public class Int16 : IConvertible {
    ...
    public bool ToBoolean() {
        return Convert.ToBoolean(this.value);
    }
    ...
}

public class Convert {
    ...
    public static bool ToBoolean(short value) {
        return (value != 0);
    }
    ...
}

Or the core types could be the ones doing the work.

public class Int16 : IConvertible {
    ...
    public bool ToBoolean() {
        return (this.value != 0);
    }
    ...
}

public class Convert {
    ...
    public static bool ToBoolean(short value) {
        value.ToBoolean();
    }
    ...
}

I chose the first way since the ECMA draft doesn't even list the core data
types as implementing IConvertible. Some of these conversions have specific
truncation rules and bounds checking, so any hard reasons on which class
should be the one to do it? Both? Neither ;)?

The other problem is with the ECMA draft, .NET SDK docs, and the corlib
implementation. At the start of the draft for System.Convert there is a
table listing all possible conversion scenerios. For instance there is no
conversion from char to boolean, and the spec does not list System.Covnert
having a public static bool ToBoolean(char value).

However, with the beta 2 SDK you can call that function or any other
non-specified conversion, it will just throw an InvalidCastException. This
leads me to believe MS' implemetation is of scenerio 2 above. Every core
data type implements IConvertible and in doing so they are forced to define
invalid conversions (i.e. Single has to define a ToChar), and those calls
probably just throw an exception.

Then in writing System.Convert they just did every possible ToType1(Type2)
function as straight calls to Type2.ToType1(), even the functions that
weren't defined in the ECMA spec.

Derek Holden