134k views
1 vote
If nullable reference types are enabled, which of the following statements stores a null value in the variable named description?

a. string description = null;
b. string? description = null;
c. string! description = null;
d. string description = #nullable;

1 Answer

3 votes

Final answer:

The correct statement to store a null value in a variable with nullable reference types enabled is 'b. string? description = null;'. The '?' indicates that the variable is a nullable reference type, allowing null assignment.

Step-by-step explanation:

If nullable reference types are enabled in a programming environment that supports them (such as C# starting with version 8.0), the correct way to store a null value in a variable specifically designed to hold nullable references is by declaring the variable with a question mark after the type. The correct statement from the provided options is:

  • b. string? description = null;

The question mark (?) after the type string indicates that the variable description is a nullable reference type. It allows for null to be explicitly assigned to it without generating a compiler warning or error, which would otherwise happen if nullable reference types were enabled and you tried to assign null to a non-nullable reference type.

Option a would normally be acceptable in code where nullable reference types aren't enabled or being enforced. Option c is not valid syntax in C# for nullable reference types, as the exclamation mark (!) is used for null-forgiving operator, not for declaring a variable. Option d is also incorrect; it appears to be a mix-up and does not represent valid C# syntax for assigning a null value to a variable.

User Muhammedv
by
8.6k points