Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable type ending with ?

What does ? mean:

public bool? Verbose { get; set; }

When applied to string?, there is an error:

The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

like image 854
MicMit Avatar asked May 19 '10 08:05

MicMit


2 Answers

? makes your non-nullable (value) types nullable. It doesn't work for string, as it is reference type and therefore nullable by default.

From MSDN, about value types:

Unlike reference types, a value type cannot contain the null value. However, the nullable types feature does allow for values types to be assigned to null.

? is basically a shorthand for Nullable<T> structure.

If you want to know more, MSDN has a great article regarding this topic.

like image 98
Ondrej Slinták Avatar answered Sep 19 '22 21:09

Ondrej Slinták


The ? is shorthand for the struct below:

struct Nullable<T>
{
    public bool HasValue;
    public T Value;
}

You can use this struct directly, but the ? is the shortcut syntax to make the resulting code much cleaner. Rather than typing:

Nullable<int> x = new Nullable<int>(125);

Instead, you can write:

int? x = 125;

This doesn't work with string, as a string is a Reference type and not a Value type.

like image 27
Neil Knight Avatar answered Sep 22 '22 21:09

Neil Knight