Variable type ending with ?

前端 未结 7 2066
别跟我提以往
别跟我提以往 2021-01-04 11:08

What does ? mean:

public bool? Verbose { get; set; }

When applied to string?, there is an error:

相关标签:
7条回答
  • 2021-01-04 11:42

    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).

    0 讨论(0)
  • 2021-01-04 11:46

    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

    0 讨论(0)
  • 2021-01-04 11:46

    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.

    0 讨论(0)
  • 2021-01-04 11:49

    ? 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.

    0 讨论(0)
  • 2021-01-04 11:50

    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 .

    0 讨论(0)
  • 2021-01-04 11:55

    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>.

    0 讨论(0)
提交回复
热议问题