Variable type ending with ?
What does ?
mean:
public bool? Verbose { get; set; }
When applied to string?
, there is an er开发者_如何学Pythonror:
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.
bool?
is a short form for System.Nullable<bool>
. Only value types are accepted for the type parameter and not reference types (like e.g. string).
bool?
is a shorthand notation for Nullable<bool>
. In general, the documentation states:
The syntax T? is shorthand for Nullable, where T is a value type. The two forms are interchangeable
Since string
is not a value type (it's a reference type), you cannot use it as the generic parameter to Nullable<T>
.
The ? operator indicates that the property is in fact a nullable type.
public bool? Verbose { get; set; }
is equilvalent to
public Nullable<bool> Verbose { get; set; }
A nullable type is a special type introduced in c# 2.0 which accepts a value type as a generic praramater type and allow nulls to be assigned to the type.
The nullable type only accept value types as generic arguments which is why you get a compile error when you try to use the ? operator in conjunction with the string type.
For more information: MSDN Nullable Types
Only value types can be declared as Nullable. Reference types are bydefault nullable. So you cannot make nullable string since string is a reference type.
the ?
means that your value type can have a null value, specially in the case of database
handling you need these nullables to check if some value is null or not.
It can be applied to only value types coz reference types can be null .
精彩评论