Topic : Nullable types | Null | The Null Coalescing Operator (??) |

Nullable Types:

Nullable type is an special data types of C# to which we can assign normal range of values as well as Null values. A Nullable type can represent the correct range of values for its underlying value types. and an additional null value. For example, a Nullable of int32, can be assigned any value from -2147483648 to 2147483647 or it can be assigned the Null value. A Nullable <bool> can assigned the values true, false or Null.

The ability to assign null to Numeric and Boolean types is especially useful when we are dealing with databases and other data types that contain element that may not be assigned a value.



Declaring Nullable Types:

Defining a nullable type is very similar to defining the equivalent non-nullable type. The difference is in the use of the ? type modifier. To define an integer, you normally would do a simple declaration:



int variableName = 1;


To make variableName able to store a null value, you would declare it as such:



int? variableName =1;


As we can see, these two variables look as though they are the same. The nullable version, however, is much different. The nullable version is actually a structure that combines a value type with a flag to indicate whether the value is null. Additionally, a nullable type has two publicly readable properties, HasValue and value . HasValue is a bool that is true if there is a value stored; otherwise, it is false if the variable is null. If HasValue is true, you can get the value of the variable. If it is false and you attempt to get the value, an exception will be thrown. Additionally, it can be assigned to a nullable variable. The following are two valid assignments for a nullable variable:



double? variableName1 = 3.141514;
double? variableName2 = null;


As We can see, variableName1 is assigned a value, but could also be assigned null. In the second statement, variableName2 is initialized to contain a null value—something we can't do with a non-nullable type.



Using Nullable Type:

A nullable type can be used in the same way that a regular value type can be used. In fact, implicit conversions are built in for converting between a nullable and non-nullable variable of the same type. This means we can assign a standard integer to a nullable integer and vice versa:



int? var1 = null;
int  var2 = 2;
    
var1 = var2;   //valid statement:
var1 = 123;    //valid statement:
var2 = var1;   //valid statement;
    
var1 = null;   //valid statement:
var2 = var1;   //exception, second is Non-nullable.



In Above Statements, we can see that a nullable and non-nullable variable can exchange values as long as the nullable variable does not contain a null. If it contains a null, an exception is thrown. Let's have an example here to know how we can declare and use the nullable variables.



/*Example: Nullables : InfoBrother:*/

using System;

namespace nullables
{
    class Program
    {
        static void Main(string[] args)
        {
            int? var1 = null;
            int? var2 = 25;
            double? var3 = new double?();
            double? var4 = 3.14157;

            bool? boolval = new bool?();


            // display the values
            Console.WriteLine("Nullables at Show: Var1:{0}, var2:{1}, var3:{2}, var4:{3}"
                              , var1, var2, var3, var4);

            Console.WriteLine("A Nullable boolean value: {0}", boolval);
            Console.ReadLine();
        }
    }
}


The Null Coalescing Operator (??):

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand. in the syntax:


  • In the Syntax:
    x  ??  y

    » x is the first operand which is a variable of a nullable type.
    » y is the second operand which has a non-nullable value of the same type


If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand. The following example explains this:


/*Example: Nullables : InfoBrother:*/

using System;

namespace nullables
{
    class Program
    {
        static void Main(string[] args)
        {
            double? var = null;
            double? var1 = 3.14157;
            double  var2;

            var2 = var ?? 5.34;  //return var2 value:
            Console.WriteLine(" Value of var2: {0}", var2);

            var = var1 ?? 5.34;  //return var1 value:
            Console.WriteLine(" Value of var: {0}", var);

            var1 = var ?? 5.34;  //return var1 value:
            Console.WriteLine(" Value of var1: {0}", var2);
            Console.ReadLine();
        }
    }
}


  • More About Nullable types:

    » Nullable types can only be used with value types.
    » The Value property will throw an InvalidOperationException if value is null; otherwise it will return the value.
    » The HasValue property returns true if the variable contains a value, or false if it is null.
    » You can only use == and != operators with a nullable type. For other comparison use the Nullable static class.
    » Nested nullable types are not allowed. Nullable<Nullable<int>> i; will give a compile time error.



  • Points to Remember:

    » Nullable<T> type allows assignment of null to value types.
    » ? operator is a shorthand syntax for Nullable types.
    » Use value property to get the value of nullable type.
    » Use HasValue property to check whether value is assigned to nullable type or not.
    » Static Nullable class is a helper class to compare nullable types.

















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement