Practice mode C#

What is printed by: object o = “hi”; Console.WriteLine(o is string s ? s.Length : -1);?

Correct answer A. 2

Explanation

The declaration pattern o is string s tests the run-time type of o and, if it matches, assigns the converted value to the new variable s. Here o refers to the string "hi", so the test succeeds and s.Length is 2. If o had held an int, the pattern would fail and the conditional would yield -1. No separate cast is needed.

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.