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?
ToInt32(String) Converts the specified string representation of a number to an equivalent 32-bit signed integer.
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.
Convert. ToInt32 allows null value, it doesn't throw any errors Int. parse does not allow null value, and it throws an ArgumentNullException error.
ToUInt16() Method in C# This method is used to convert the value of the specified Decimal to the equivalent 16-bit unsigned integer.
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 IConvertible
s 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With