views:

277

answers:

7

What does that mean ?

public bool? Verbose { get; set; }

When applied to string? , there is an error

Error 11 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'

+16  A: 

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

Ondrej Slinták
+5  A: 

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

Anders Abel
+4  A: 

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

klausbyskov
+14  A: 

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.

Ardman
+1  A: 

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

Beansy
+1  A: 

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.

this. __curious_geek
+1  A: 

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 .

Praveen