Microsoft.CSharp.Nullable Class
The Microsoft.CSharp.Nullable class provides helper methods for working with nullable value types at runtime. It is primarily used by the C# compiler when dealing with the ? nullable modifier.
public static class Microsoft.CSharp.Nullable
{
public static bool IsNull(object value);
public static object GetValueOrDefault(object nullable);
public static object GetValueOrDefault(object nullable, object defaultValue);
}
Methods
- IsNull(object value)
Returnstrueif the suppliedvalueis a boxed nullable type whoseHasValueproperty isfalse, otherwisefalse. - GetValueOrDefault(object nullable)
Returns the underlying value of a boxed nullable type, or the default value of the underlying type ifHasValueisfalse. - GetValueOrDefault(object nullable, object defaultValue)
Returns the underlying value of a boxed nullable type, ordefaultValueifHasValueisfalse.
Remarks
All methods accept object parameters to support reflection scenarios where the exact nullable type is not known at compile time.
using System;
using Microsoft.CSharp;
class Program
{
static void Main()
{
int? nullableInt = null;
object boxed = nullableInt; // boxed nullable
bool isNull = Nullable.IsNull(boxed); // true
int value = (int)Nullable.GetValueOrDefault(boxed); // 0
nullableInt = 42;
boxed = nullableInt;
isNull = Nullable.IsNull(boxed); // false
value = (int)Nullable.GetValueOrDefault(boxed, -1); // 42
Console.WriteLine($"IsNull: {isNull}, Value: {value}");
}
}