Click here to Skip to main content
13,194,662 members (57,750 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

3.4K views
4 bookmarked
Posted 18 Dec 2016

Nullable Type and Null Coalescing Operator

, 18 Dec 2016
Rate this:
Please Sign up or sign in to vote.
Nullable Type and Null Coalescing Operator

Introduction

We will learn two points in this tip:

  • Nullable types in C#
  • Null Coalescing operator in C#

Nullable Types in C#

There are two types of data types in C#:

  • Value Types: int, float, decimal, etc.
  • References Types: Interfaces, Class, Delegates, Arrays, etc.

All value types are non nullable types in C#, make them nullable type use ? operator.

  • int i = 3 is non nullable
  • int? i null is nullable

Point is why C# introduced nullable types.

  1. Nullable types are very helpful for optional fields. You don't get it. Wait for a moment, we understand it through an example.

    Let us suppose we have 3 fields in a given example.

    using System;
    
    namespace NullableType
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Enter FN");
                string firstName = Console.ReadLine();
    
                Console.WriteLine("Enter LN");
                string lastName = Console.ReadLine();
    
                Console.WriteLine("Are you Minor(true/false)");
                string minor = Console.ReadLine();
    
                bool? areYouMinor = null;
    
                if (!string.IsNullOrEmpty(minor))
                {
                   areYouMinor = Convert.ToBoolean(minor);
                }
    
                Console.WriteLine("Output:\n______________");
                Console.WriteLine("First Name:{0}",firstName);
                Console.WriteLine("Last Name:{0}", lastName);
    
                if (areYouMinor == true)
                {
                    Console.WriteLine("Are You Minor : Yes");
                }
                else if (areYouMinor == false)
                {
                    Console.WriteLine("Are You Minor : No");
                }
                else
                {
                    Console.WriteLine("Are You Minor : Did not provide the value");
                }
    
                Console.ReadLine();
            }
        }
    }

    In this example, if user does not provide the value for third field, then the output will be:

  2. Nullable types bridge between C# types and database types.

    It means database does not have any value type or reference type, you can store null in any type in database.

    Counter part in Nullable type is Null Coalescing operator.

Null Coalescing Operator in C#

Null Coalescing operator is used when you have to assign some value if field has null value.

You did'nt get it again, wait for a moment. We will try to understand it through an example.

using System;

namespace NullCoalescingOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            int? itemsOnSale = null;
            int availableItems;

            if (itemsOnSale == null)
            {
                availableItems = 0;
            }
            else
            {
                availableItems = (int)itemsOnSale;
            }

            Console.WriteLine("Available Items are {0}",availableItems);
            Console.ReadLine();
        }
    }
}

In this example, if itemOnSale field has null value, then output will be:

Apart from that, we write the above example with the help of null coalescing operator.

using System;

namespace NullCoalescingOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            int? itemsOnSale = null;
            int availableItems = itemsOnSale ?? 0;
                        
            Console.WriteLine("Available Items are {0}",availableItems);
            Console.ReadLine();
        }
    }
}

The output will be the same...

...but it makes our code neat and clean and this is the beauty of null coalescing operator.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Lakshya Dyal
India India
I am Lakshya Dyal, working as senior software developer in Admiral Technologies and have 6+ years of expreince in .NET technologies.

You may also be interested in...

Pro

Comments and Discussions

 
Question[My vote of 2] Better choice Pin
Kirk Wood20-Dec-16 1:32
memberKirk Wood20-Dec-16 1:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171018.2 | Last Updated 18 Dec 2016
Article Copyright 2016 by Lakshya Dyal
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid