Practice mode C#

What happens when this C# code runs: int? n = null; int x = n.Value;?

Correct answer D. An InvalidOperationException is thrown

Explanation

The code compiles because Nullable.Value is an int. At run time, however, Value throws InvalidOperationException when HasValue is false. It does not quietly return 0; that is what GetValueOrDefault() does. Safer patterns are int x = n ?? 0; or checking if (n.HasValue) or n is int v before reading the value.

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.