BCA / B.Tech 8 min read

Nullable Types in .NET

Nullable Types in .NET in Hindi |  Nullable Types in .NET in Hindi:


  • In .NET, Nullable types are used for data types that need to accept a null value.
  •  For example, Value Types like int, double, and bool cannot be null by default, but you can give them a null value through Nullable types.
  • Nullable types are very useful in .NET for situations when Value Types need a null value. This makes the code secure, readable, and easy.
What are Nullable Types?

  • A nullable type is a data type that can hold a value as well as null. It is defined in .NET as System.Nullable<T>.
Example: If you are storing data from a database column and that column can be empty, then you will use a Nullable type.

int? age = null; // This is a Nullable int, which can accept a null value.

  • Nullable types are only useful for Value Types (like int, double). Reference Types (like string) can already be null.
  • Use the Value property only when HasValue is true, otherwise it will give an Exception.

Example:

using System;

class Program
{
    static void Main()
    {
        int? age = null; // Nullable type
        Console.WriteLine("Age: " + (age.HasValue ? age.Value.ToString() : "No value"));

        age = 30;
        Console.WriteLine("Age: " + age ?? "No value"); // Null Coalescing Operator
    }
}


How to declare Nullable Types?

Using a Question Mark (?): You can make a Value Type Nullable by putting a ? after it.

int? age = null;
double? salary = 50000.50;
Using System.Nullable<T>:

You can also create Nullable types using a generic type.

Nullable<int> age = null;
Nullable<double> salary = 100000.75;

Why use Nullable Types?

  • Storing Null values: Useful in situations when data is unavailable.
  • Working with databases: For database columns that can be empty (null).
  • Conditional programming: Helps in making logical decisions, such as when a value is present or not.

Working with Nullable Types:

1. HasValue and Value Properties: HasValue: This checks if the Nullable type has a value or not.
Value: This is used to get the value.

int? age = 25;
if (age.HasValue)
{
    Console.WriteLine("Age: " + age.Value);
}
else
{
    Console.WriteLine("Age is null");
}

2. Null Coalescing Operator (??): This operator helps in setting a default value.

int? age = null;
int defaultAge = age ?? 18; // If age is null, then defaultAge will be 18.
Console.WriteLine(defaultAge);

3. Null-Conditional Operator (?.): This operator safely checks if a value is null.

int? age = null;
Console.WriteLine(age?.ToString() ?? "No age available");
Cast and Boxing with Nullable Types

Boxing: When converting a Nullable type to an Object.

int? num = 10;
object obj = num; // Boxing
Console.WriteLine(obj);

Unboxing: Converting from an Object to a Nullable type.

object obj = null;
int? num = (int?)obj; // Unboxing
Console.WriteLine(num);