1

I came across a problem and I think I have the solution but cannot find anyone to tell me if I am right or wrong? See sample in C# below:

public void Test(float number)
{
   object myObj = number;

  //Here is where I don't know what the correct way to do this is?
  // int newNumber = (int)myObj;
  // int newNumber = (int)(float)myObj;
 // int newNumber = (int)(double)myObj;
}

The result has to ensure no type exceptions occur. Any idea's guys?

Josh
  • 569
  • 1
  • 11
  • 35

4 Answers4

1

The second option is the right one.

First, you unbox your value by casting it to the exact type that was originally boxed (i.e. float).
And then you convert float to int.

Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
1

Since the type of boxed value is float, you need to cast it to float first because it needs to be unboxed:

int newNumber = (int)(float)myObj;

You can find more information from these questions if you wonder the reason of double cast:

Community
  • 1
  • 1
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • Oh I guess that's where I was confused. I thought since it originally started out as a float object and a float can be casted to a int I could simply do (int)myObject. – Josh May 15 '14 at 14:50
1

Let's try each...

//int newNumber = (int)myObj;
//InvalidCastException: Specified cast is not valid.

int newNumber = (int)(float)myObj; // works! newNumber is 2

//int newNumber = (int)(double)myObj;
//InvalidCastException: Specified cast is not valid.

When you have such a boxed numeric value and wish to convert it with casting, you must first cast it to the exact type (in this case, float) before converting it to a compatible type (in this case, int).

If you don't know ahead of time that it's a float, but you do know it can be converted to int, you should use Convert.ToInt32, which will work whether myObj is a float, double, etc.

int newNumber = Convert.ToInt32(myObj);
Tim S.
  • 55,448
  • 7
  • 96
  • 122
1

According to your test you don't know type of boxed value then I'd avoid any double casting (because for first one you'll always need to know exact type).

There is a class to work with conversion, let's try to use it:

int number = Convert.ToInt32(myObj, null);

Actually that's pretty different from plain casting, it'll perform something like this:

int number = ((IConvertible)myObj).ToInt32(null);

Difference is how rounding is performed. Cast will truncate your number (so 1.7 will become 1) while conversion will perform a rounding (so 1.7 will become 2).

If you're aware it's a floating point number (but you don't know if double or float) then I'd suggest to first convert to double then cast:

int number = (int)Convert.ToDouble(myObj, null);

See also my answer about difference between casting and conversion.

Community
  • 1
  • 1
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208