0
0
C Sharp (C#)programming~5 mins

Nullable value types in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Sometimes, you want to store a value that can also be empty or missing. Nullable value types let you do that with simple data like numbers or dates.

When you want to represent a number that might not have a value yet, like a test score that hasn't been entered.
When working with dates that might be unknown, like a person's date of death if they are still alive.
When reading data from a database where some fields can be empty.
When you want to check if a value was set or left blank in a form.
When you want to avoid using special values like -1 to mean 'no value'.
Syntax
C Sharp (C#)
int? myNumber;
Nullable<int> myOtherNumber;

You can add a question mark ? after a value type to make it nullable.

Alternatively, use Nullable<T> where T is a value type.

Examples
This example shows a nullable integer age that starts empty (null). We check if it has no value.
C Sharp (C#)
int? age = null;
if (age == null) {
    Console.WriteLine("Age is unknown.");
}
Here, a nullable double holds a value. We use HasValue to check if it has data, then print it.
C Sharp (C#)
Nullable<double> temperature = 36.6;
if (temperature.HasValue) {
    Console.WriteLine($"Temperature: {temperature.Value}");
}
You can assign a value or null to a nullable type anytime.
C Sharp (C#)
int? score = 85;
score = null; // now score has no value
Sample Program

This program starts with a nullable integer testScore that has no value. It prints a message. Then it sets a value and prints it.

C Sharp (C#)
using System;

class Program {
    static void Main() {
        int? testScore = null;

        if (testScore == null) {
            Console.WriteLine("Test score is not set yet.");
        }

        testScore = 90;

        if (testScore.HasValue) {
            Console.WriteLine($"Test score is {testScore.Value}.");
        }
    }
}
OutputSuccess
Important Notes

Nullable types are useful to avoid errors when a value might be missing.

Use .HasValue to check if there is a value, and .Value to get it safely.

Trying to get .Value when there is no value causes an error.

Summary

Nullable value types let you store normal values or no value (null).

Use ? after a type or Nullable<T> to create them.

Always check if a nullable has a value before using it.