Nullable<T>
type is also a value type.Nullable
Type is ofstruct
type that holds a value type (struct
) and aBoolean
flag, namedHasValue
, to indicate whether the value isnull
or not.- Since
Nullable<T>
itself is a value type, it is fairly lightweight. The size ofNullable<T>
type instance is the same as the size of containing value type plus the size of aboolean
. - The
nullable
types parameterT
isstruct
. i.e., you can usenullable
type only with value types. This is quite ok because reference types can already benull
. You can also use theNullable<T>
type for your user definedstruct
. Nullable
type is not an extension in all the value types. It is astruct
which contains a generic value type and aboolean
flag.
Nullable<int> i = 1;
Nullable<int> j = null;
Use
Value
property of Nullable
type to get the value of the type it holds. As the definition says, it will return the value if it is not null
, else, it will throw an exception. So, you may need to check for the value being null
before using it.
Console.WriteLine("i: HasValue={0}, Value={1}", i.HasValue, i.Value);
Console.WriteLine("j: HasValue={0}, Value={1}", j.HasValue, j.GetValueOrDefault());
//The above code will give you the following output:
i: HasValue=True, Value=5
j: HasValue=False, Value=0
Conversions and Operators for Nullable Types
C# also supports simple syntax to use
Nullable
types. It also supports implicit conversion and casts on Nullable
instances. The following example shows this:
// Implicit conversion from System.Int32 to Nullable<Int32>
int? i = 5;
// Implicit conversion from 'null' to Nullable<Int32>
int? j = null;
// Explicit conversion from Nullable<Int32> to non-nullable Int32
int k = (int)i;
// Casting between nullable primitive types
No comments:
Post a Comment