<p>Which of the following is better code in c# and why?</p>

<pre><code>((DateTime)g[0]["MyUntypedDateField"]).ToShortDateString()
</code></pre>

<p>or</p>

<pre><code>DateTime.Parse(g[0]["MyUntypedDateField"].ToString()).ToShortDateString()
</code></pre>

<p>Ultimately, is it better to cast or to parse?</p>

[{'answer_id': 61740, 'author': 'Wilka', 'author_id': 1367, 'author_profile': 'https://Stackoverflow.com/users/1367', 'pm_score': 5, 'selected': True, 'text': '<p>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)</p>\n'}, {'answer_id': 61743, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 0, 'selected': False, 'text': '<p>As @Brian R. Bondy pointed it depends on implementation of <strong>g[0]["MyUntypedDateField"]</strong>. Safe practice is to use <strong>DateTime.TryParse</strong> and <strong>as</strong> operator. </p>\n'}, {'answer_id': 61768, 'author': 'Ryan Farley', 'author_id': 1627, 'author_profile': 'https://Stackoverflow.com/users/1627', 'pm_score': 0, 'selected': False, 'text': '<p>Parse requires a string for input, casting requires an object, so in the second example you provide above, then you are required to perform two casts: one from an object to a string, then from a string to a DateTime. The first does not.  </p>\n\n<p>However, if there is a risk of an exception when you perform the cast, then you might want to go the second route so you can TryParse and avoid an expensive exception to be thrown. Otherwise, go the most efficient route and just cast once (from object to DateTime) rather than twice (from object to string to DateTime).</p>\n'}, {'answer_id': 61771, 'author': 'sgwill', 'author_id': 1204, 'author_profile': 'https://Stackoverflow.com/users/1204', 'pm_score': 0, 'selected': False, 'text': '<p>There\'s comparison of the different techniques at <a href="http://blogs.msdn.com/bclteam/archive/2005/02/11/371436.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/bclteam/archive/2005/02/11/371436.aspx</a>. </p>\n'}, {'answer_id': 61931, 'author': 'qbeuek', 'author_id': 5348, 'author_profile': 'https://Stackoverflow.com/users/5348', 'pm_score': 2, 'selected': False, 'text': '<p>Casting is the <strong>only</strong> good answer.</p>\n\n<p>You have to remember, that ToString and Parse results are not always exact - there are cases, when you cannot safely roundtrip between those two functions.</p>\n\n<p>The documentation of ToString says, it uses current thread culture settings. The documentation of Parse says, it also uses current thread culture settings (so far so good - they are using the same culture), but there is an explicit remark, that:</p>\n\n<blockquote>\n  <p>Formatting is influenced by properties of the current DateTimeFormatInfo object, which by default are derived from the Regional and Language Options item in Control Panel. <strong>One reason the Parse method can unexpectedly throw FormatException is if the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator properties are set to the same value.</strong></p>\n</blockquote>\n\n<p>So depending on the users settings, the ToString/Parse code can and will unexpectedly fail...</p>\n'}, {'answer_id': 62619, 'author': 'Steve Cooper', 'author_id': 6722, 'author_profile': 'https://Stackoverflow.com/users/6722', 'pm_score': 1, 'selected': False, 'text': '<p>Your code suggests that the variable may be either a date or a string that looks like a date. Dates you can simply return wit a cast, but strings must be parsed. Parsing comes with two caveats;</p>\n\n<ol>\n<li><p>if you aren\'t certain this string can be parsed, then use <code>DateTime.TryParse()</code>. </p></li>\n<li><p>Always include a reference to the culture you want to parse as. <code>ToShortDateString()</code> returns different outputs in different places. You will almost certainly want to parse using the same culture. I suggest this function dealing with both situations;</p>\n\n<pre><code>private DateTime ParseDateTime(object data)\n{\n    if (data is DateTime)\n    {\n        // already a date-time.\n        return (DateTime)data;\n    }\n    else if (data is string)\n    {\n        // it\'s a local-format string.\n        string dateString = (string)data;\n        DateTime parseResult;\n        if (DateTime.TryParse(dateString, CultureInfo.CurrentCulture,\n                              DateTimeStyles.AssumeLocal, out parseResult))\n        {\n            return parseResult;\n        }\n        else\n        {\n            throw new ArgumentOutOfRangeException("data", \n                               "could not parse this datetime:" + data);\n        }\n    }\n    else\n    {\n        // it\'s neither a DateTime or a string; that\'s a problem.\n        throw new ArgumentOutOfRangeException("data", \n                              "could not understand data of this type");\n    }\n}\n</code></pre></li>\n</ol>\n\n<p>Then call like this;</p>\n\n<pre><code>ParseDateTime(g[0]["MyUntypedDateField").ToShortDateString();\n</code></pre>\n\n<p>Note that bad data throws an exception, so you\'ll want to catch that.</p>\n\n<p>Also; the \'as\' operator does not work with the DateTime data type, as this only works with reference types, and DateTime is a value type.</p>\n'}]
['https://Stackoverflow.com/questions/61733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4246/']