title: Double-casting required to convert from int as object to float
body: <p>Here's a weird one I ran into.  I've got a function that returns an <code>object</code>.  In a particular case, I know for sure that object is an <code>int</code>, but another function calling this function requires a <code>float</code>.  The only way I could get this to work was the following:</p>
  
  <pre><code>private object parser(string expr) {...}
  
  private float parseFloat(string expr)
  {
      ...
      object result = parser(expr);
      if (result is int)
          return (float)(int)result;
      else
          return (float)result;
  }
  </code></pre>
  
  <p>Without that type-check, I couldn't get it to work at all, even though I knew the result of the parser function in this case was an <code>int</code>.  (You could see it in the debugger.)  I'd prefer the line to go simply:</p>
  
  <pre><code>private float parseFloat(string expr)
  {
      ...
      return (float)parser(expr);
  }
  </code></pre>
  
  <p>(Type checking is done beforehand, and <code>parseFloat</code> should never be called with an expression that will not evaluate to a <code>float</code> or <code>int</code>.)  Is there some reason why it's necessary to double-cast this variable?  I obviously don't want to double-cast it in all cases, because if the return from <code>parser</code> <em>was</em> a <code>float</code>, it would truncate it to <code>int</code> first and we don't want that.  (And yes, I tried replacing <code>float</code> and <code>int</code> with <code>Single</code> and <code>Int32</code>, etc.  Didn't make any difference.)</p>
  
  <p>I saw <a href="https://stackoverflow.com/questions/4352697/cant-cast-float-to-int-if-object">this question</a>, but it depends on knowing the type in advance, and the only solution it offers is this double-casting trick, which in my case would truncate <code>float</code>s unless I do a type-check first, which also requires an additional local variable to hold the result.  Is there any way to avoid that extra step?</p>