Skip to content

Instantly share code, notes, and snippets.

@tugberkugurlu
Last active November 11, 2016 08:55
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 tugberkugurlu/3bf3fab29335f3e23421002faf62c9b6 to your computer and use it in GitHub Desktop.
Save tugberkugurlu/3bf3fab29335f3e23421002faf62c9b6 to your computer and use it in GitHub Desktop.
It's not a perfect solution but at least allows you to create non-lying method signatures. Origin: https://twitter.com/tourismgeek/status/796771077531848706 and https://codeblog.jonskeet.uk/2008/10/06/non-nullable-reference-types/
using System;
/// <summary>
/// Wraps a reference type value which should not be null.
/// </summary>
/// <typeparam name="T"></typeparam>
public struct NonNullable<T> where T : class
{
private readonly T _value;
/// <exception cref="ArgumentNullException">Thrown when the reference type <see cref="T" /> value is <code>null</code>.</exception>
public NonNullable(T value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
_value = value;
}
/// <summary>
/// Unwaraps the reference type value of <see cref="NonNullable{T}" /> as <see cref="T" />.
/// </summary>
/// <remarks>See https://msdn.microsoft.com/en-us/library/ms229054(v=vs.100).aspx on why this is a method rather than a property.</remarks>
/// <returns>The reference type <see cref="T" /> value.</returns>
/// <exception cref="InvalidOperationException">Thrown when the reference type <see cref="T" /> value is <code>null</code>.</exception>
public T GetValue()
{
if (_value == null)
{
throw new InvalidOperationException($"Cannot access the Value of '{GetType()}' when it is null");
}
return _value;
}
public override string ToString() => GetValue().ToString();
public override int GetHashCode() => GetValue().GetHashCode();
public override bool Equals(object obj) => GetValue().Equals(obj);
/// <exception cref="InvalidOperationException">Thrown when the reference type <see cref="T" /> value is <code>null</code>.</exception>
public static implicit operator T(NonNullable<T> value)
{
return value.GetValue();
}
/// <exception cref="ArgumentNullException">Thrown when the reference type <see cref="T" /> value is <code>null</code>.</exception>
public static implicit operator NonNullable<T>(T value)
{
return new NonNullable<T>(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment