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

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

If it is not supported, why does it exist? Doesn't it make sense to just not have this feature?

+8
c # datetime converter
source share
2 answers

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

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

Thus, the method in question exists in the Convert class, probably because all IConvertible must have this method:

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

So, it seems like others have noted, it seems that this is a matter of consistency with the IConvertible interface and completeness. A Convert implementation can even be generated, as it relies only on IConvertible .

+4
source share

My previous guess about code generation was wrong. This is actually much simpler: almost all implementations of the IConvertible interface in DateTime throw an InvalidCastException . These calls are always called when you call Convert.ToXXX() , as you can see here:

Convert.ToInt64 :

 public static long ToInt64(DateTime value) { return ((IConvertible)value).ToInt64(null); } 

Bottom line? Microsoft wanted to implement the IConvertible interface in DateTime , but did not want to provide implementations for any conversion other than ToDateTime , ToString and ToType .

+3
source share

All Articles