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
@Timwi
I agree, which is why I think this type would require compiler support. There is a proposal for this on Roslyn #227.
This type alone would be useless as variables. It would only be useful as method parameters and properties. Using it for fields leads to the default(T) issue.