C# - Are Nullable types reference types?
Nullable types in C# are not reference types; they are actually value types. They allow you to assign a value or a special null value to value types like int, float, and bool. Nullable types are represented by the Nullable<T>
struct, or you can use the shorthand T?
notation, where T
is the underlying value type.
Here's a complete source code example to illustrate nullable types in C#:
using System;
class Program
{
static void Main()
{
int? nullableInt = null;
double? nullableDouble = 3.14;
bool? nullableBool = true;
Console.WriteLine("Nullable Int: " + nullableInt);
Console.WriteLine("Nullable Double: " + nullableDouble);
Console.WriteLine("Nullable Bool: " + nullableBool);
if (nullableInt.HasValue)
{
Console.WriteLine("Nullable Int has a value: " + nullableInt.Value);
}
else
{
Console.WriteLine("Nullable Int is null");
}
if (nullableDouble.HasValue)
{
Console.WriteLine("Nullable Double has a value: " + nullableDouble.Value);
}
else
{
Console.WriteLine("Nullable Double is null");
}
if (nullableBool.HasValue)
{
Console.WriteLine("Nullable Bool has a value: " + nullableBool.Value);
}
else
{
Console.WriteLine("Nullable Bool is null");
}
}
}
Output:
Nullable Int:
Nullable Double: 3.14
Nullable Bool: True
Nullable Int is null
Nullable Double has a value: 3.14
Nullable Bool has a value: True
In this example, we declare three nullable variables: nullableInt, nullableDouble, and nullableBool. We set nullableInt to null, nullableDouble to 3.14, and nullableBool to true. Then, we use the HasValue property to check if they have a value or are null.
As you can see, nullable types allow us to assign null to value types and still perform checks to determine if they have a value or not. This is helpful when you need to represent missing or undefined data in your applications.