Skip to content

Instantly share code, notes, and snippets.

@GeirGrusom
Created February 27, 2015 07:10
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 GeirGrusom/0c766c6f80c9d3e38d91 to your computer and use it in GitHub Desktop.
Save GeirGrusom/0c766c6f80c9d3e38d91 to your computer and use it in GitHub Desktop.
Not null reference type
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();
}
}
@iamkoch
Copy link

iamkoch commented Feb 27, 2015

You could make a non-defaultable value type, too.

@Timwi
Copy link

Timwi commented Mar 2, 2015

This doesn’t really work. You can write default(NotNull<string>) and you get a “not-null” that is null. If you think this is pedantic because you can just avoid writing that: that’s short-sighted, because lots of generic code uses default(T) in its implementation, so to avoid this, you’d have to avoid ever using NotNull<string> as a generic type argument.

@GeirGrusom
Copy link
Author

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment