Freigeben über


Nullable Value Types

Can you assign null to int?? Read carefully before you answer, this is a trick question! You can do that by using nullable value types:

int? x = null;

To check if the nullable value has a value, you can use the .HasValue property. If the value is null, it won't throw a null reference exception, it will just return false, otherwise, it returns true. To get the value, there are several ways, like typecasting it to int or using the .Value property, but you need to check for the value first:

int? x = null;
string s = x.ToString(); // x.Value.ToString() if not null or string.Empty otherwise.
int y;

y = x.GetValueOrDefault(); // x.Value if not null or default(int) otherwise.
y = x.GetValueOrDefault(13); // x.Value if not null or 13 otherwise.
y = (int)x; // InvalidOperationException: Nullable object must have a value.
y = x.Value; // InvalidOperationException: Nullable object must have a value.
// y = x; // Compile Error: Cannot implicitly convert type 'int?' to 'int'.

For more info, please read: Nullable Types, Using Nullable Types, and Boxing Nullable Types