1

I'm having a weird issue.

I'm receiving "Cannot cast from source type to destination type"-exception when trying to cast from double to float, but I can't understand why and why this (see below) works any different.

//this throws exception
void doSomething1(object val)
{
   if(val is double || val is float)
   {
      doSomethingElse((float)val);
   }
}

//this works
void doSomething2(object val)
{
   if(val is double || val is float)
   {
      double tmpDouble = (double)val;
      float tmpFloat = (float)tmpDouble;
      doSomethingElse(tmpFloat);
   }
}

void doSomethingElse(float val)
{
//do something
}

I've checked the Type of val and it is System.Double, so what is wrong here?

EDIT: Someone flagged this has duplicate (which it kinda is), but the exception I received is not the same as the one received in the "duplicate"-post and thus I could not locate this exact problem (especially since I was stupid enough to not understand it was an (un)boxing issue).

Whyser
  • 2,187
  • 2
  • 20
  • 40
  • 1
    Unboxing doesn't consider conversions, you can only unbox a double to `double` or `double?`. – CodesInChaos Mar 04 '18 at 12:17
  • So, `(float)(double)val` for val having type `System.Double`. – user202729 Mar 04 '18 at 12:19
  • Your second code will fail if the value is a `float`. – CodesInChaos Mar 04 '18 at 12:19
  • https://msdn.microsoft.com/en-us/library/kx3x7f55(v=vs.110).aspx and then cast to float – Marco Mar 04 '18 at 12:20
  • [Related](https://stackoverflow.com/questions/15565196/how-to-unbox-from-object-to-type-it-contains-not-knowing-that-type-at-compile-t). – user202729 Mar 04 '18 at 12:20
  • Ahh thank you all for your quick answers! And thanks for the related question @user202729 . It helped me understand my issue more clearly! – Whyser Mar 04 '18 at 12:24
  • Be careful -- dupe questions tend to be downvoted ("this question does not show any research effort"). – user202729 Mar 04 '18 at 13:09
  • As a C# dev but non-expert in these boxing issues, I also agree see that the marked duplicate is *related* but not really/clearly pointing to the solution to the problem. I voted to reopen, so someone can post a clear solution. However, there seems to be some debate in the review queue (alternating "Reopen"s and "Leave closed"s) :/ – Pac0 Mar 08 '18 at 13:57

0 Answers0