Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have several options:</p> <ul> <li><p><code>(int)</code> &mdash; Cast operator. Works if the object <em>already is</em> an integer at some level in the inheritance hierarchy or if there is an implicit conversion defined.</p></li> <li><p><code>int.Parse()/int.TryParse()</code> &mdash; For converting from a string of unknown format.</p></li> <li><p><code>int.ParseExact()/int.TryParseExact()</code> &mdash; For converting from a string in a specific format</p></li> <li><p><code>Convert.ToInt32()</code> &mdash; For converting an object of unknown type. It will use an explicit and implicit conversion or IConvertible implementation if any are defined.</p></li> <li><p><code>as int?</code> &mdash; Note the "?". The <code>as</code> operator is only for reference types, and so I used "?" to signify a <code>Nullable&lt;int&gt;</code>. The "<code>as</code>" operator works like <code>Convert.To____()</code>, but think <code>TryParse()</code> rather than <code>Parse()</code>: it returns <code>null</code> rather than throwing an exception if the conversion fails.</p></li> </ul> <p>Of these, I would prefer <code>(int)</code> if the object really is just a boxed integer. Otherwise use <a href="http://msdn.microsoft.com/en-us/library/system.convert.toint32.aspx" rel="noreferrer"><code>Convert.ToInt32()</code></a> in this case.</p> <p>Note that this is a very <em>general</em> answer: I want to throw some attention to Darren Clark's response because I think it does a good job addressing the <em>specifics</em> here, but came in late and wasn't voted as well yet. He gets my vote for "accepted answer", anyway, for also recommending (int), for pointing out that if it fails <code>(int)(short)</code> might work instead, and for recommending you check your debugger to find out the actual runtime type.</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