Skip to content

Instantly share code, notes, and snippets.

@PoisonousJohn
Forked from JohannesEH/Example.cs
Created March 21, 2017 07:29
Show Gist options
  • Save PoisonousJohn/4943d84e210b908e18a7a6cf2f0875c7 to your computer and use it in GitHub Desktop.
Save PoisonousJohn/4943d84e210b908e18a7a6cf2f0875c7 to your computer and use it in GitHub Desktop.
How to make a non-nullable type wrapper in C#, today… (doesn't work, for blog)
public void DoStuff(object input)
{
if (input == null)
throw new ArgumentNullException("input");
// Method implementation...
}
public struct NonNull<T> where T : class
{
private readonly T _value;
public T Value { get { return _value; } }
public NonNull(T instance)
{
if (instance == null)
throw new ArgumentNullException("instance", "The \"instance\" parameter must not be null.");
_value = instance;
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
public override bool Equals(object obj)
{
return _value.Equals(obj);
}
public static bool operator ==(NonNull<T> valueA, NonNull<T> valueB)
{
return valueA._value == valueB._value;
}
public static bool operator !=(NonNull<T> valueA, NonNull<T> valueB)
{
return valueA._value != valueB._value;
}
public static implicit operator NonNull<T>(T value)
{
return new NonNull<T>(value);
}
public static explicit operator T(NonNull<T> value)
{
return value._value;
}
}
public struct NonNull<T> where T : class
{
private readonly T _value;
public T Value { get { return _value; } }
[Obsolete("The default parameterless constructor has been disabled please use NonNull<T>(T instance) constructor instead.", true)]
public NonNull(object dummy)
{
throw new NotSupportedException("The default parameterless constructor has been disabled please use NonNull<T>(T instance) constructor instead.");
}
public NonNull(T instance)
{
if (instance == null)
throw new ArgumentNullException("instance", "The \"instance\" parameter must not be null.");
_value = instance;
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
public override bool Equals(object obj)
{
return _value.Equals(obj);
}
public static bool operator ==(NonNull<T> valueA, NonNull<T> valueB)
{
return valueA._value == valueB._value;
}
public static bool operator !=(NonNull<T> valueA, NonNull<T> valueB)
{
return valueA._value != valueB._value;
}
public static implicit operator NonNull<T>(T value)
{
return new NonNull<T>(value);
}
public static explicit operator T(NonNull<T> value)
{
return value._value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment