70-483 Exam QuestionsBrowse all questions from this exam

70-483 Exam - Question 17


You are implementing a method named Calculate that performs conversions between value types and reference types. The following code segment implements the method. (Line numbers are included for reference only.)

Exam 70-483 Question 17

You need to ensure that the application does not throw exceptions on invalid conversions.

Which code segment should you insert at line 04?

Show Answer
Correct Answer: A

To ensure that the application does not throw exceptions on invalid conversions, the correct code segment to insert at line 04 is: int balance = (int) (float) amountRef;. The initial conversion (float) amountRef takes the object amountRef and unboxes it back to a float, which is its original type. Then (int) casts the float to an int, ensuring that the final conversion is valid. Simply casting amountRef directly to an int, as in options B and C, would result in a runtime exception because amountRef is originally a float boxed inside an object. Option D is incorrect because amountRef is of type float, not double.

Discussion

6 comments
Sign in to comment
Idoudist
Mar 14, 2020

correct , (float) amountRef convert object to float (int) (float) amountRef convert (float) amountRef to int , this way we make sure that code does not throw exception by directly casting amountRef to int , B false

tanujgyan
Mar 31, 2020

A is correct answer

robinnirola
Apr 20, 2020

A. int balance = (int) (float)amountRef;

lh2607
Jul 11, 2020

A is correct

Gobe
Oct 7, 2020

int balance = (int)amountRef; doesn't show compile time error, why is that?

Tomtidom
Jan 5, 2021

It does throw an invallid cast exception at runtime

misbelieving
Sep 22, 2021

A: (float) unboxes the float from object, (int) casts the float to int