Variable type ending with ?

限于喜欢 提交于 2019-11-30 18:53:43

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!