Created
October 28, 2015 14:24
-
-
Save yfakariya/4abca54df34e24f1757c to your computer and use it in GitHub Desktop.
IsNull revised
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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