Nullable types:
A Nullable type was introduced in C# 2.0 as a value type. Microsoft introduced these types for solving the problem of assigning default values to value types at the time of value type declaration.
Nullable types allow the value types that they will accept the null values instead of default values.
’?’ modifier is used in Nullable types after the data types and that allows the null values for that type.
The type before the ‘?’ modifier is known as underlying type of Nullable types.
The underlying type of Nullable types is either a value type or any parameter that is considere to value types but it won’t be reference type
int?,double ? are valid for Nullable types but string? is not a Nullable type
The underlying type must be itself a Nullable type.
If we define an object like T?, it is a alias for system.nullable
An object of a Nullable type has two public properties:
· Hasvalue:
Hasvalue property is used for bool types. If an instance’s Hasvalue is true, then that is said to be non null. If Hasvalue is false then that instance has null value .
The default value for Hasvalue is false.
· Value:
If we assign any value to instance of a Nullable type,then value property returns that value. Otherwise it throws an exception.
There is no default value for this property.
Example:
Class N
{
Static void main (string[] args)
{
int? n = null;
if (n.Hasvalue == true)
{
Console.writeLine (“n value is”+ n.value );
}
else
{
Console.writeline ( “n value is null”);
}
}
}
No comments:
Post a Comment