Nullable in C#
Nullable Types:
v A
value type cannot be assigned a null value. For example, int i = null will give
you a compile time error.
v C#
2.0 introduced nullable types that allow you to assign null to value type
variables.
v The
Nullable type allows you to assign a null value to a variable. Nullable types
can only work with Value Type, not with Reference Type.
v In
nullable of integer type you can store values from -2147483648 to 2147483647,
or null value.
v Nullable
types do not support var type. If you use Nullable with var, then the compiler
will give you a compile-time error.
v The
main use of nullable type is in database applications. Suppose, in a
table a column required null values, then you can use nullable type to enter
null values.
v Nested
Nullable types are not allowed. Nullable<Nullable<int>> i; will
give a compile time error.
Syntax:
1.
Nullable<data_type>
variable_name = null;
2.
datatype? variable_name =
null;
Example:
// this will give compile time error
int j = null;
// Valid declaration
Nullable<int> j = null;
// Valid declaration
int? j = null;
double? d = null;
Access Nullable Value:
v We
cannot directly access the value of the Nullable type. Either we have to use .value or
GetValueOrDefault() method.
v Nullable.value
gives runtime error if value is null.
v GetValueOrDefault()
method to get an original assigned value if it is not null.
v You
will get the default value if it is null. The default value for null will be
zero.
Nullable.HasValue:
v If
the object assigned with a value, then it will return “True”.
v If
the object is assigned to null, then it will return “False”
v If
the object is not assigned with any value then it will give compile-time error.
null coalescing operator (?? Operator):
v Use
the '??' operator to assign a nullable type to a non-nullable type.
v C#
2.0 introduced the?? Or null coalescing operator.
The?? operator has two operands and can be used in an expression as follows:
x = y?? z;
v The??
operator returns the left-hand operand if the left-hand operand is not null,
otherwise it returns the right-hand operand. In the example above, if ‘y’ is
not null, then ‘x’ is set to ‘y’; however, if ‘y’ is null, then ‘x’ is set to
‘z’.
Comments
Post a Comment