Created
August 28, 2012 20:04
-
-
Save munr/3503540 to your computer and use it in GitHub Desktop.
RangeField
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
public class RangeField<T> | |
{ | |
private T Start { get; set; } | |
private T End { get; set; } | |
public RangeField() | |
{ | |
Start = default(T); | |
End = default(T); | |
} | |
public static RangeField<T> New(T val) | |
{ | |
return new RangeField<T> { Start = val, End = val }; | |
} | |
public static RangeField<T> New(T start, T end) | |
{ | |
return new RangeField<T> { Start = start, End = end }; | |
} | |
public bool HasRange() | |
{ | |
return HasStart() && HasEnd(); | |
} | |
public bool HasStart() | |
{ | |
return (!IsNullOrDefault(Start)); | |
} | |
public bool HasEnd() | |
{ | |
return (!IsNullOrDefault(End)); | |
} | |
private static bool IsNullOrDefault<T>(T argument) | |
{ | |
// deal with normal scenarios | |
if (argument == null) | |
return true; | |
if (object.Equals(argument, default(T))) | |
return true; | |
// deal with non-null nullables | |
Type methodType = typeof(T); | |
if (Nullable.GetUnderlyingType(methodType) != null) | |
return false; | |
// deal with boxed value types | |
Type argumentType = argument.GetType(); | |
if (argumentType.IsValueType && argumentType != methodType) | |
{ | |
object obj = Activator.CreateInstance(argument.GetType()); | |
return obj.Equals(argument); | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment