If I have a value D and want to ensure it is type datetime then is there a difference between the following?
DateTime dtm = Convert.ToDateTi
By using the "Convert" class you can actually convert between different types. E.g. you can convert a String into a DateTime. Casting only works on the same types. So you can not cast a String into an Int32 as this would raise a cast exception.
Regarding your example: If the content of D is always of the DateTime type then you should prefer casting it because a cast is very fast. In case you don't know what type is inside D (maybe because it's of Object type) you might want to prefer converting it as this is more elegant than just plain casting because this method allows you to set the DateTime also by String (Date String) or by Int32 (ticks).
Convert.ToDateTime
has several overloads that will convert other types to DateTime
. It should be used when you're converting an instance that isn't a DateTime to a DateTime instance. You could also use DateTime.Parse and DateTime.TryParse (if you're trying to parse a string representation).
(DateTime)D
attempts to directly cast an instance to DateTime
. If the instance isn't already a DateTime
prior to the call, an exception will be thrown.