Why is there a method like this in the .NET Framework?

Looking at the metadata, I found this function: (in the class "System.Convert")

    //
    // Summary:
    //     Calling this method always throws System.InvalidCastException.
    //
    // Parameters:
    //   value:
    //     The date and time value to convert.
    //
    // Returns:
    //     This conversion is not supported. No value is returned.
    //
    // Exceptions:
    //   System.InvalidCastException:
    //     This conversion is not supported.
    public static bool ToBoolean(DateTime value);

Why is Microsoft doing this?

+4
source share
5 answers

The Convert class is very convenient for handling boxed field types. The C # hard rule states that you should always unpack it into the same type:

    object box = 42;
    long value = (long)box;  // Kaboom!

This throws an InvalidCastException. Pretty inconvenient, especially since converting int to long is never a problem otherwise. However, it was necessary to make unboxing effective, very important in .NET 1.x before generics were available.

IConvertable. :

    object box = 42;
    long value = Convert.ToInt64(box);  // No problem

, - . . , , , . Convert.ToBoolean(DateTime) , , .

+6

MSDN, Convert.ToBoolean(DateTime) .

, , , . , DateTime , .

+5

Convert. , : Convert.ToDateTime, DateTimes, Convert.ToSTring, DateTimes Strings. , , , , , .

+2

Because someone from Microsoft decided that he System.Convertshould have a method to convert to / from each primitive type, regardless of whether conversion is possible.

Please note that there are several ways:

Convert.ToDateTime(Boolean value)
Convert.ToBoolean(Char value)

and most methods ToChar.

+1
source

Thus, this causes a Link error :

    DateTime actualdate;
    bool canNotConvert = Convert.ToBoolean(actualdate);
0
source

All Articles