Site icon Dotnet Helpers

Nullable Types

Nullable Types

Nullable types are variables that can be assigned with the value ‘null’. Allmost all value types can be declared as a nullable type. To declare a
value type as a nullable type, you have to add a questionmark after the type name.

For example:

char? a = null;
bool? b = null;
int? c = null;
double? d = null;

Nullable type has two read-only properties: HasValue and Value.
HasValue is a bool property. If the current value is ‘null’,
HasValue will return false, otherwise it will return true. The HasValue property can be used to test if a variable contains a value.

For Example :

int? test = 10;
if (test .HasValue)
{
Console.WriteLine(test .Value);
}
else
{
Console.WriteLine(“no value”);
}

How to convert Nullable Type to NON-Nullable Type

int? intValue1 = null;
int intValue2  = intValue1  ?? 10;

Exit mobile version