Practice mode C#

What happens when this C# code runs: object o = 5; long n = (long)o;?

Correct answer A. An InvalidCastException is thrown

Explanation

The value 5 is boxed as an int. Unboxing must be to the exact type that was boxed (or its nullable form), so casting the boxed int directly to long throws InvalidCastException at run time, even though int converts to long normally. The correct form is long n = (int)o;, which first unboxes to int and then widens implicitly to long.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.