C# - Nullable Data Types Example

Learn, what are nullable data types with the help of example in C#.
Submitted by Nidhi, on September 11, 2020 [Last updated : March 22, 2023]

Nullable Data Types

Variable declared as a nullable type that can store normal values as well as null values. To declare a nullable data type, we use question mark (?) symbol.

C# program to demonstrate the example of Nullable data types

The source code to demonstrate the Nullable data types is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to demonstrate the Nullable data types in C#

using System;

class NullableDemo
{
    static void Main(string[] args)
    {
        int? intVal1 = null;
        int? intVal2 = 786;

        float?  floatVal1 =  3.14F;
        float? floatVal2 = new float?();

        bool?   boolval = new bool?();
        
        Console.WriteLine("Nullable Integers : {0}, {1}",intVal1,intVal2);
        Console.WriteLine("Nullable Floats   : {0}, {1}", floatVal1, floatVal2);
        Console.WriteLine("Nullable boolean  : {0}", boolval);
    }
}

Output

Nullable Integers : , 786
Nullable Floats   : 3.14,
Nullable boolean  :
Press any key to continue . . .

Explanation

In the above program, we created a class NullableDemo that contains the Main() method. In the Main() method we created nullable variables using a question mark. Variable declared as a nullable type that can store normal values as well as null values, here we will question mark to declare a variable as a nullable. 

Then printed the values of all variables on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.