John Virgolino John Virgolino - 1 month ago 7
C# Question

C# Casting vs. Parse

This may seem rudimentary to some, but this question has been nagging at me and as I write some code, I figured I would ask.

Which of the following is better code in c# and why?

((DateTime)g[0]["MyUntypedDateField"]).ToShortDateString()


or

DateTime.Parse(g[0]["MyUntypedDateField"].ToString()).ToShortDateString()


Ultimately, is it better to cast or to parse? Thanks all!

Answer

If g[0]["MyUntypedDateField"] is really a DateTime object, then the cast is the better choice. If it's not really a DateTime, then you have no choice but to use the Parse (you would get an InvalidCastException if you tried to use the cast)