NullableTypeCsharp

Nullable types in C#

Nullable types in C#

C# types are divided into below two categories:

  1. Value Types: int, float, double, struct etc.
  2. Reference Type: string, class, Interface, delegates, arrays etc.
  • By default value types are non nullable. To have nullable value type we have to use ?
  • Nullable type is work like bridge between C# types and Database Types.
  • int a=0 (a is non nullable variable, can’t assign null to this variable)
  • int? a= null (a is nullable int variable, so we can assign null value)
  • string str=null (string is a reference type, so we could assign null directly to string type variable)

Let’s understand using below example:

using System;

namespace NullableTypesCsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            bool? isEmployee = null;

            if (isEmployee.HasValue)
            {
                if (isEmployee == true)
                    Console.WriteLine("He is employee of this company.");
                else
                    Console.WriteLine("He is not employee of this company.");
            }
            else
                Console.WriteLine("He is not employee of this company.");

            Console.ReadKey();
        }
    }
}

Output:

He is not employee of this company.

Another example with int datatype: 

using System;

namespace NullableTypesCsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int? NoOfAvailableJobs = 10;

            int FinalJobAvailable;

            if (!NoOfAvailableJobs.HasValue)
                FinalJobAvailable = 0;
            else
                FinalJobAvailable = NoOfAvailableJobs.Value;

            Console.WriteLine("Final Jobs available: " + FinalJobAvailable);

            Console.ReadKey();
        }
    }
}

Output:

Final Jobs available: 10

 

In above example, you can notice that we have used “NoOfAvailableJobs.Value“, which will return int so we could directly assign to our FinalJobAvailable variable. Please refer below image for your reference

NullableTypeCsharp

 

Here we could also use single line of code instead of writing these much lines as below

//if (!NoOfAvailableJobs.HasValue)
//    FinalJobAvailable = 0;
//else
//    FinalJobAvailable = NoOfAvailableJobs.Value;

FinalJobAvailable = NoOfAvailableJobs ?? 0;

 

Leave a Reply