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

IsNull

Unified advanced generic check for: DbNull.Value, INullable.IsNull, !Nullable<>.HasValue, null reference. Omits boxing for value types.

Source

[DebuggerStepThrough]
public static bool IsNull<T>
    (this T me)
{
    if (me is INullable && (me as INullable).IsNull) return true;
    var type = typeof (T);
    if (type.IsValueType)
    {
        if (!ReferenceEquals(Nullable.GetUnderlyingType(type), null) && me.GetHashCode() == 0) return true;
    }
    else
    {
        if (ReferenceEquals(me, null)) return true;
        if (Convert.IsDBNull(me)) return true;
    }
    return false;
}
[DebuggerStepThrough]
public static bool IsNull<T>
    (this T? me)
    where T : struct
{
    return !me.HasValue;
}

Example

object a = null;
int? b = null;
var c = DBNull.Value;
var d = SqlInt32.Null;
Console.WriteLine(a.IsNull());
Console.WriteLine(b.IsNull());
Console.WriteLine(c.IsNull());
Console.WriteLine(d.IsNull());

Author: Den

Submitted on: 4 sep. 2011

Language: C#

Type: System.Object

Views: 8317