IsNull

[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());

Description

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

Details

  • Author: Den
  • Submitted on: 9/4/2011 10:52:57 AM
  • Language: C#
  • Type: System.Object
  • Views: 3328

Double click on the code to select all.

 

;