Nullable Types And The Null Coalescing Operator in C#

This article explains what nullable types are, what the null coalescing operator is, and how to use the null-coalescing operator in  C#.

Nullable types are a bridge between a database and C# code, allowing nulls to be transformed for use in C# code.

Null Coalescing operators make it easier to check for nulls and shorten C# code when dealing with nulls.

Nullable types

In C#, nullable types are value-type variables that can be assigned null values.

The following are examples of the value and reference types:

  • Value Types: int, float, double, DateTime.
  • Reference Types: Classes, arrays, delegates, and so on.

The default value of a reference type is null, but the default value of a value type is some kind of value, which means that value types are not nullable by default, so whenever we use a value type, the default value should be provided for those types.

Example

Int i=0;
Bool isPresent=true;
Float j=0;

The compiler message indicates that null is being assigned to the int data type in the example above.

The solution to this problem is to make the value type nullable.

The solution to this problem is to make the value type nullable.

Nullable types are System instances.

The Nullable<T> struct.

For example, if we use Nullable<Int32>, we can assign any value between -2147483648 and 2147483647 as an int, as well as the null value.

How do you make a non-nullable value type nullable? is being used.

int i=0 (null is not Possible): non-nullable type
i=null int (null is Possible ): nullable type

Let’s Understand with an example

Example

We have a number of fields like name, age, etc, and Ex-employee is a non-mandatory field, which means the user can choose not to enter a value for this when entering the detail, so null could be one of the answers.

class Program
    {
        static void Main(string[] args)
        {
            string a = null;
            //int= null;
            bool? exEmployee = null;
            if (exEmployee == true)
            {
                Console.WriteLine("User is an ex employee of orgainization!!!!");
            }
            else if (exEmployee == false)
            {
                Console.WriteLine("User is not an ex employee of orgainization!!!!");
            }
            else
            {
                Console.WriteLine("User has not entered the required detail!!!!");
            }
            Console.ReadLine();

        }
    }

Database data types do not have a value type or a reference type like C# code.

So, wherever the we works with C# and a database, we must deal with null values stored in the database and retrieved by C# code for further processing.

Nullable types serve as a bridge between a database and C# code, allowing nulls to be transformed and used in C# code.

Notes

  • Nullable types are value-type variables that can have the value “NULL” assigned to them. A nullable type cannot be created from a reference type.
  • A Nullable Type is a struct type that contains a value type (struct) and a Boolean flag, HasValue, that indicates whether or not the value is null.
  • Nullable types cannot be nested. The line below will not compile: Nullable<Nullable<int>> n;
  • Nullable<t> is a value type that is relatively lightweight.

Null Coalescing Operator (??)

The ?? operator is known as the null-coalescing operator.

If the operand is not null, it returns the left-hand operand; otherwise, it returns the right-hand operand. In other words, the Null Coalescing Operator (??) is a binary operator for checking for null values. It is compatible with both nullable and reference types.It is written as I j, which means that if I is not null, then evaluate it to I otherwise to J.

There is no implicit conversion of a nullable type to a non-nullable type in this case. As a result, the explicit convention should be required to compile the code.

“.value” is returning an int type.

Sample Code for Example

namespace nullableType
{
        class Program
        {
            static void Main(string[] args)
            {
                int? _Discount = 10;
                int Discount;
                if (_Discount == null)
                {
                    Discount = 0;
                }
                else
                {
                    Discount = _Discount.Value;
                }
                Console.WriteLine("No Of discounted Items are :" + Discount);
                //   using coalescing  operator (??)   
                int discountedItem = _Discount ?? 0;
                Console.WriteLine("No Of discounted Items are : (with coalescing ) " + Discount);
                Console.ReadLine();

                Console.ReadLine();
            }
        
        }
}

The code will now compile and give desired results.

Submit a Comment

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

Subscribe

Select Categories