Created
February 27, 2015 07:10
-
-
Save GeirGrusom/0c766c6f80c9d3e38d91 to your computer and use it in GitHub Desktop.
Not null reference type
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 struct NotNull<T> | |
where T : class | |
{ | |
private readonly T _value; | |
private NotNull(T value) | |
{ | |
_value = value; | |
} | |
public static implicit operator NotNull<T>(T value) | |
{ | |
if (value == null) | |
throw new ArgumentNullException("value"); | |
return new NotNull<T>(value); | |
} | |
public static implicit operator T(NotNull<T> value) | |
{ | |
return value._value; | |
} | |
public T Value { get { return _value; } } | |
public override string ToString() | |
{ | |
return _value.ToString(); | |
} | |
public override bool Equals(object obj) | |
{ | |
return _value.Equals(obj); | |
} | |
public override int GetHashCode() | |
{ | |
return _value.GetHashCode(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn’t really work. You can write
default(NotNull<string>)
and you get a “not-null” that isnull
. If you think this is pedantic because you can just avoid writing that: that’s short-sighted, because lots of generic code usesdefault(T)
in its implementation, so to avoid this, you’d have to avoid ever usingNotNull<string>
as a generic type argument.