Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It really depends on whether you know if <code>o</code> is a string and what you want to do with it. If your comment means that <code>o</code> really really is a string, I'd prefer the straight <code>(string)o</code> cast - it's unlikely to fail.</p> <p>The biggest advantage of using the straight cast is that when it fails, you get an <a href="http://msdn.microsoft.com/en-us/library/system.invalidcastexception.aspx" rel="noreferrer">InvalidCastException</a>, which tells you pretty much what went wrong.</p> <p>With the <code>as</code> operator, if <code>o</code> isn't a string, <code>s</code> is set to <code>null</code>, which is handy if you're unsure and want to test <code>s</code>:</p> <pre><code>string s = o as string; if ( s == null ) { // well that's not good! gotoPlanB(); } </code></pre> <p>However, if you don't perform that test, you'll use <code>s</code> later and have a <a href="http://msdn.microsoft.com/en-us/library/system.nullreferencetexception.aspx" rel="noreferrer">NullReferenceException</a> thrown. These tend to be more common and a <em>lot</em> harder to track down once they happens out in the wild, as nearly every line dereferences a variable and may throw one. On the other hand, if you're trying to cast to a value type (any primitive, or structs such as <a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx" rel="noreferrer">DateTime</a>), you have to use the straight cast - the <code>as</code> won't work.</p> <p>In the special case of converting to a string, every object has a <code>ToString</code>, so your third method may be okay if <code>o</code> isn't null and you think the <code>ToString</code> method might do what you want.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload