Skip to content

Instantly share code, notes, and snippets.

@yfakariya
Created October 28, 2015 14:24
Show Gist options
  • Save yfakariya/4abca54df34e24f1757c to your computer and use it in GitHub Desktop.
Save yfakariya/4abca54df34e24f1757c to your computer and use it in GitHub Desktop.
IsNull revised
using System;
static class Program
{
static void Main()
{
Test( "a" );
Test( 1 );
Test<int?>( 1 );
}
static void Test<T>( T nonNull)
{
Console.WriteLine( "IsNull<{0}>(default({0})) :{1}", typeof( T ).Name, NullChecker<T>.IsNull( default( T ) ) );
Console.WriteLine( "IsNull<{0}>(nonNull) :{1}", typeof( T ).Name, NullChecker<T>.IsNull( nonNull ) );
}
}
internal static class NullChecker<T>
{
private static readonly Func<T, bool> _isNull =
InitializeIsNull();
private static Func<T, bool> InitializeIsNull()
{
if ( !typeof( T ).IsValueType )
{
return value => value == null;
}
var nullableUnderlyingType = Nullable.GetUnderlyingType( typeof( T ) );
if ( nullableUnderlyingType != null )
{
return
( Func<T, bool> )
typeof( NullableNullChecker<> )
.MakeGenericType( nullableUnderlyingType )
.GetMethod( "IsNull" )
.CreateDelegate( typeof( Func<T, bool> ) );
}
return _ => false;
}
public static bool IsNull( T value )
{
return _isNull( value );
}
}
internal static class NullableNullChecker<T>
where T : struct
{
public static bool IsNull( Nullable<T> value )
{
return !value.HasValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment