user3596113
user3596113

Reputation: 878

Unboxing a boxed float to an int

I'm preparing for an exam and stumbled over a question regarding boxing/unboxing. I always thought if i box let's say a float like this:

float x = 4.5f;
object o = x;

If a want a value type variable back from o, I will have to unbox it to a float.

float y = (float)o;

This should throw an exception:

int z = int(o);

If I want to cast the value stored in o to an int I will have to unbox it first and cast afterwards like this:

int z = (int)(float)o;

Now the question i stumbled upon:

Suppose you have a method like this:

public static void FloorTemperature(float degrees) {
    object degreesRef = degrees;
    `xxx`
    Console.WriteLine(result);
}

You need to ensure the application does not throw exceptions on invalid conversions. Which code segment should you insert for xxx (I think invalid conversion are invalid cast exceptions):

(a) int result = (int)degreesRef; (b) int result = (int)(float)degreesRef;

The correct solution is (a), but to me (b) looks correct. So can you please enlighten me? What am I missing?

Kind regards

Upvotes: 2

Views: 1395

Answers (1)

Christo S. Christov
Christo S. Christov

Reputation: 2309

You aren't missing anything

The answer should be (b) because:

(a) throws an exception since you are trying to cast object to int.

(b) is correct since you first cast it to float then you cast it to int which rounds it but doesn't throw an exception.

Upvotes: 5

Related Questions