Skip to content

Instantly share code, notes, and snippets.

@falahati
Last active February 20, 2017 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save falahati/3fae30cd1e48e7531a382ced4cf81ac6 to your computer and use it in GitHub Desktop.
Save falahati/3fae30cd1e48e7531a382ced4cf81ac6 to your computer and use it in GitHub Desktop.
C#: This is a copy of System.Nullable<T> class that can be used for both reference types and value types
internal class Nullable<T>
{
public static Nullable<T> Null = new Nullable<T>();
private readonly bool _hasValue;
private Nullable()
{
_hasValue = false;
}
public Nullable(T value)
{
Value = value;
_hasValue = true;
}
public T Value { get; }
public bool HasValue
{
get
{
if (typeof(T).IsValueType)
{
return _hasValue;
}
return Value != null;
}
}
public override bool Equals(object other)
{
var otherNullable = other as Nullable<T>;
if (otherNullable != null)
{
if (!otherNullable.HasValue && !HasValue)
{
return true;
}
if (otherNullable.HasValue && HasValue && otherNullable.Value.Equals(Value))
{
return true;
}
return false;
}
if (other is T && HasValue && ((T) other).Equals(Value))
{
return true;
}
if ((other == null) && !HasValue)
{
return true;
}
return false;
}
public override int GetHashCode()
{
if (HasValue)
{
return Value.GetHashCode();
}
return 0;
}
public T GetValueOrDefault()
{
return GetValueOrDefault(default(T));
}
public T GetValueOrDefault(T defaultValue)
{
return HasValue ? Value : defaultValue;
}
public override string ToString()
{
return HasValue ? Value.ToString() : "";
}
public static implicit operator Nullable<T>(T value)
{
return new Nullable<T>(value);
}
public static explicit operator T(Nullable<T> value)
{
return value.Value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment