Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why theres a Method like this one in .NET Framework? [duplicate]

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

    //
    // 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 Microsoft do this?

like image 326
Marcel James Avatar asked Dec 09 '22 12:12

Marcel James


2 Answers

The Convert class is very handy to deal with boxed value types. A hard C# rule says that you must always unbox it to the exact same type:

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

That generates an InvalidCastException. Pretty inconvenient, especially since converting an int to a long is never a problem otherwise. It was however necessary to make unboxing efficient, very important in .NET 1.x before generics were available.

Every value type implements the IConvertable interface. Which make this code work to solve the problem:

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

While this looks pretty synthetic, the real use case is reading data from a dbase. You'll get the column values as boxed values. And clearly it is very possible to have an oops where a column is a Date value and the program tries read it as a Boolean. The Convert.ToBoolean(DateTime) method ensures that you'll get a loud bang when that happens.

like image 187
Hans Passant Avatar answered Jan 12 '23 05:01

Hans Passant


According to MSDN, Convert.ToBoolean(DateTime) is reserved for future use.

They've most likely added it in there to prevent backwards compatibility issues down the road if this is implemented. However, what converting a DateTime to a Boolean means, is completely beyond me.

like image 22
Mike Christensen Avatar answered Jan 12 '23 04:01

Mike Christensen