ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Nullable Coalesce

Coalesce any like nullable types.

Source

internal static T? Coalesce<T>(this T? nullable, params T?[] args) where T : struct
{
    if (nullable.HasValue)
    {
        return nullable.Value;
    }

    T? result = null;

    foreach (var arg in args.Where(arg => arg.HasValue))
    {
        result = arg.Value;
        break;
    }

    return result;
}

Example

DateTime? never = null;
DateTime? now = DateTime.Now;

var sut = never.Coalesce(now);
Assert.IsTrue(sut.HasValue);
Assert.AreEqual(now, sut);

Author: David Michael Pine

Submitted on: 1 jun. 2015

Language: C#

Type: C# Generics

Views: 4255