What is the Nullable helper class?
'Nullable<T>' struct, also known as the nullable value type, which allows value types to hold null values. The 'Nullable<T>' struct is not a helper class but rather a built-in struct in the C# language and the .NET Framework.
The 'Nullable<T>' struct is used to wrap a value type 'T' and provide additional functionality to represent both the actual value and the null state. This is particularly useful when dealing with value types (such as 'int', 'float', 'bool', etc.) that can't normally be assigned a 'null' value.
Here's the basic syntax to declare a nullable value:
Nullable<T> nullableValue; // or use the shorthand notation T?
For example, declaring a nullable integer:
int? nullableInt;
You can then assign a value to the nullable variable, including null, and check its null state using the 'HasValue' property and access the underlying value using the 'Value' property.
int? nullableInt = null;
int? anotherNullableInt = 42;
if (nullableInt.HasValue)
{
Console.WriteLine("nullableInt has a value: " + nullableInt.Value);
}
else
{
Console.WriteLine("nullableInt is null");
}
int result = nullableInt ?? 0; // Assign 0 if nullableInt is null
Console.WriteLine("anotherNullableInt: " + anotherNullableInt);
Console.WriteLine("NullableInt with null-coalescing: " + result);
As of C# 2.0, C# introduced syntactic sugar to make working with nullable types more convenient, and you can use the shorthand notation 'T?' instead of 'Nullable<T>':
int? nullableInt = null;
Behind the scenes, the compiler handles the 'Nullable<T>' struct, allowing you to work with nullable values without the need for explicit instantiation of 'Nullable<T>'.
Comparison operators don’t work if nullable type variable has null value. Null is considered to be less than any value. For eample in the code mentioned below j is neither less than k, greater than k, nor equal to k.
using System;
class Program
{
static void Main()
{
withoutnullableHelperClass();
}
static void withoutnullableHelperClass()
{
int? j = null;
int k = 100;
if (j < k)
Console.WriteLine("j < k");
else if (j > k)
Console.WriteLine("j > k");
else if (j == k)
Console.WriteLine("j == k");
else
Console.WriteLine("sorry couldn't compare.");
}
}
Output:
sorry couldn't compare.
'Nullable' helper class is a static class which provides 'Compare' method to compare nullable types. It also provides a 'GetUnderlyingType' method that returns underlying type argument of nullable type.
Let’s understand it with an example:
using System;
class Program
{
static void Main()
{
withnullableHelperClass();
}
void withnullableHelperClass()
{
int? j = null;
int k = 100;
if (Nullable.Compare(j,k) < 0)
Console.WriteLine("j < k");
else if (Nullable.Compare(j, k) > 0)
Console.WriteLine("j > k");
else
Console.WriteLine("j equals k");
}
}
Output:
J < k