Nullable Types in C#

In C# types are divded into 2 broad categories:

  1. Value types - int, float, double, structs, enums, etc.
  2. Reference types - Interface, Class, delegates, arrays, etc.
by default value types are non nullable. TO make them nullable use ?

  • int i = 0 (i is non nullable, so i cannot be set to null, i = null will generate compiler error)
  • int? j = 0 (j is nullable int, so j = null is legal)
Nullable types bridge the difference between C# types and database types

Below program shows the compiler error that we get if we try to set the null value to the value types.



Write a program to check is user is married or not. Set boolean variable to null while writing the program.


using System;
class Program
{
    static void Main()
    {
        bool? isMarried = null;

        if (isMarried == true)
            Console.WriteLine("User is married");
        else if (isMarried == true)
            Console.WriteLine("User is not married");
        else
            Console.WriteLine("User did not answer the question");
    }
}

Output:


Null coalescing operator

Write a program to assign a value of TicketsOnSell to TicketsAvailable. If TicketsOnSell are null, assign value 0 to TicketsAvaialable.


using System;
class Program
{
    static void Main()
    {
        int? TicketsOnSale = null;
        int TicketsAvaialable = TicketsOnSale ?? 0;
        Console.WriteLine("TicketsAvaialable: " + TicketsAvaialable);
    }
}

Output


Comments

Popular posts from this blog

Introduction to C#

Common Operators in C#

Built-in types in C#