c# - parseexact - managementdatetimeconverter




What is the purpose of:public static DateTime ToDateTime(DateTime value) in the.NET Framework? (3)

I am maintaining an existing project, and I found this line of code:

Datetime someDate = ....;
var anotherDateTime = Convert.ToDateTime(someDate);

At first, I expected that someDate is converted to a string by calling the ToString method on it implicitly, but I was wrong. As I pressed F12 on the method I see the definition of that method in the System.Convert class, which is like the following:

// Summary: Returns the specified System.DateTime object; no actual conversion is performed.
// Parameters:
//   value: A date and time value.
// Returns:
//     value is returned unchanged.
public static DateTime ToDateTime(DateTime value);

First Why does the .NET framework have a method like this in the first place, as the documentation says that this method does Nothing?
Second While I am refactoring the code, can I safely remove the call for this method without affecting the behavior?


As you can see in the current BCL sources:

public static DateTime ToDateTime(DateTime value) {
        return value;
}

there is no actual conversion, so you can safely remove those calls.


It is because the Convert class is intented to work with types that implement the IConvertible interface.

This interface contains methods to convert an implementing type to CLR types like decimal, byte, DateTime etc. Each of those types implement IConvertible themselves.

So, Convert.ToDateTime(DateTime d) isn't the only method that does "nothing". It exists for any of those CLR types implementing IConvertible as well, e.g. Convert.ToChar(char c). It just comes from the fact that all of these types implement IConvertible.

You can read more about this in the comments of the source code of the Convert class.


Yes, you can remove it. It is completely redundant. As for why: I guess someone thought it was a good idea to avoid people accidentally calling Convert.ToDateTime(object) (which would be implicit) - which would involve a box, type-check and unbox. Frankly that seems like a silly reason to me, along the lines of "write bad code, get bad results".





datetime