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'
?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With