Nullable value type variables.
.Net Framework 2.0 brought us ability of having nullable value type variables. Maybe it sounds unusually but there are cases where we could use this feature. To make it happen we have to put "?" mark operator after the type, like this:
bool? booleanvalue = null;
int? integervalue = null;
short? GetShortValue()
{
return null;
}
Now variables booleanvalue and integervalue have null value. And of course we can set null value in any part of code.
For example I could use this feature to create public property with lazy load initialization:
private int? _field;
public int? Property
{
get
{
if (_field != null)
_field = 10; //Default value
return _field;
}
set { _field = value; }
}
We cannot set nullable type of variable to non nullable. We will get compile-time error.
int? integervalue = 3;
int standardInteger = integervalue; //This is wrong implementation
To achieve that we have to use new "??" operator.
int? integervalue = null;
int y = integervalue ?? 3;
In case when integervalue will have null value y variable will set to 3 otherwise to integervalue.