r/ProgrammerTIL • u/woeterman_94 • Mar 13 '18
C# TIL that there is a method to convert a boolean to a Datetime
But.. Calling this method always throws InvalidCastException. https://msdn.microsoft.com/en-us/library/yzwx168e(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
52
Upvotes
14
u/jnordwick Mar 14 '18
My birthday, not my birthday. What more does anybody need to know?
22
u/falki147 Mar 13 '18
It says on the .Net 2.0 page that it is reserved for future use. It seems like they dropped the idea of doing so.
7
u/HaniiPuppy Mar 13 '18
This seems useful.
3
u/bautin Mar 14 '18
There are methods to convert any type to any other type including converting to the same type. It does nothing.
I'm guessing this is a side effect of inheritance.
Every base type has a struct that implements the IConvertible interface. The IConvertible interface has declarations to convert to every base type.
The code for the Convert class is probably generated at least in part. And that generation probably gets all of the classes that implement IConvertible and then generates a method for all of the implemented methods. Or something along those lines. Convert exists to expose
So IConvertible requires a class to implement ToDateTime(IFormatProvider format). Boolean implements IConvertible so it has to implement ToDateTime. Whatever generates the code sees that Boolean implements IConvertible, so it generates a ToDateTime(Boolean value) method for Converter.
So instead of the work and overhead of trying to figure out which conversions should be allowed and which shouldn't in the Converter class, you let the implementers of IConvertible worry about it.
There's also ToDateTime(object value). But it will fail if value doesn't implement IConvertible. So even if ToDateTime(Boolean) didn't exist, it would exist.
I mean technically, you don't even need all of the other method signatures if you have ToDateTime(object value). You can use reflection to determine if the value has a ToDateTime method and invoke it, but if you can do less work, you should.
5
u/Goron40 Mar 14 '18
Other types that throw an InvalidCastException:
In other words, pretty much everything.
1
u/Solero93 Mar 13 '18
Invalidate legacy code maybe...?