Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a Convert.ToInt32(DateTime) method when the operation is "not supported"? [closed]

The Convert.ToInt32(DateTime) method is documented to always throw an InvalidCastException because "This conversion is not supported."

If its not supported, why does it even exist? Wouldn't it make more sense to just not have that function?

like image 510
David says Reinstate Monica Avatar asked Aug 20 '14 20:08

David says Reinstate Monica


People also ask

Why is convert ToInt32 used?

ToInt32(String) Converts the specified string representation of a number to an equivalent 32-bit signed integer.

What does convert ToInt32 mean?

ToInt32() converts a floating-point value (float, double) to a 32-bit integer value. We pass a floating-point value to this function, and it will output an Int32 type value.

What is the difference between int parse and convert ToInt32?

Convert. ToInt32 allows null value, it doesn't throw any errors Int. parse does not allow null value, and it throws an ArgumentNullException error.

What method from the Convert class can be used to convert a specified value to an 16 bit unsigned integer?

ToUInt16() Method in C# This method is used to convert the value of the specified Decimal to the equivalent 16-bit unsigned integer.


1 Answers

Looking at the Convert implementation you can see that it relies on the IConvertible interface being implemented by the types that are being converted. The IConvertible interface forces a type to implement all conversion methods, and it is intended to work as you've described:

If there is no meaningful conversion to a common language runtime type, then a particular interface method implementation throws InvalidCastException.

So the method in question exists in Convert class probably because all IConvertibles have to have this method:

public static int ToInt32(DateTime value)
{
    return ((IConvertible)value).ToInt32(null);
}

So, similar to what others have noted seems that it's a matter of consistency with IConvertible interface and completeness. The Convert's implementation might even be generated, as it only relies on IConvertible.

like image 97
BartoszKP Avatar answered Sep 30 '22 08:09

BartoszKP