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

DefaultValue

Returns a the value of a Nullable type if it has a value or it will return a default value

Source

public static T DefaultValue<T>(this Nullable<T> value, T defaultValue) where T : struct
{
    if (value == null || value.HasValue == false)
    {
        return defaultValue;
    }

    return value.Value;
}

Example

bool? HasVideo = null;
bool value = HasVideo.DefaultValue(false);

Author: Robert Booth

Submitted on: 30 mrt. 2009

Language: C#

Type: System.Nullable<T>

Views: 5006