Saturday 23 December 2017

Nullable Types


  • Nullable types represent value-type variables that can be assigned the value of null.
  • You cannot create a nullable type based on a reference type. (Reference type already support the n ull value.)
  • The syntax T? is shorthand for Nullable<T>, where T is a value type. The two forms are interchangeable.
  • Assign a value to a nullable type just as you would for an ordinary value type.
    eg:- int?X = 10; OR double?D = 4.190.
  • A nullable type can also be assigned the value null.
    eg:- int?X = null.
  • Use the Nullable<T>.GetValueOrDefault method to return either the assigned value, or the default value for the underlying type if the value is null.
    eg:- int?X = 10;
            int J = X.GetValueOrDefault();
  • Use the Hashvalue and Value read-only properties to test for null and retrieve the value.
    eg:- if(X.Hashvalue)J = X.Value;

    - The Hashvalue property returns true if the variable contains a value, or false if it is null.
    - The value property returns a value if one is assigned. Otherwise, a system.InvalidOperationException is thrown.
    - The default value for Hashvalue is false. The value property has no default value.
  • You can also use the '==' and '!=' operators with nullable type.
    eg:- if(X!=null)Y=X;
  • Use the '??' operator to assign a default value that will be applied when a nullable type whose current value is 'null' is assigned to a non-nullable type.
    eg:- int?X = null';
           int Y = X ?? -1;
  • Nested nullable types are not allowed. The following line will not compile:
    Nullable<Nullable<T>>n;

No comments:

Post a Comment