Introduction: Nullables In C#

In this post, we will learn about Nullables In C# with an example.C#.Net support a special data types, the nullable types, to which you can assign normal range of values as well as null values.

Description:

In my previous posts I have explained various topics like Collections in C#SortedSet in C#.Net,Stack in C#,Queue in C#.Net,LinkedList in C#.Net. Now in this post, I will explain about Nullables In C# with appropriate example.



For example, you may store any integer value from -2,147,483,648 to 2,147,483,647 or null in a Nullable variable. Same as, you can assign true, false, or null in a Nullable variable.

Syntax:

< data_type> ? = null;

Now open Visual Studio and create Console Application and write below line of code.

using System;
using System.Collections;

namespace ConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int? _Number1 = null;
            int? _Number2 = 78;
            double? _Number3 = new double?();
            double? _Number4 = 3.14157;

            bool? _boolval = new bool?();

            // display the values
            Console.WriteLine("All value : {0}, {1}, {2}, {3}", _Number1, _Number2, _Number3, _Number4);
            Console.WriteLine("A Nullable boolean value: {0}", _boolval);
            Console.ReadLine();  
        }
    }   
}

Nullables In C#

Nullables In C#

The Null Coalescing Operator (??)

The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible.
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 −

using System;
using System.Collections;

namespace ConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            double? _Num1 = null;
            double? _Num2 = 3.14157;
            double _Num3;
            _Num3 = _Num1 ?? 5.34;
            Console.WriteLine(" Value of _Num3: {0}", _Num3);
            _Num3 = _Num2 ?? 5.34;
            Console.WriteLine(" Value of _Num3: {0}", _Num3);
            Console.ReadLine();
        }
    }   
}

Nullables In C#

Nullables In C#

I hope you got an idea about Nullables In C#.
I would like to have feedback from my blog readers.
Your valuable feedback, question, or comments about this article are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website