Last active
August 29, 2015 14:12
-
-
Save sirtony/b787714e046d7f6f0a48 to your computer and use it in GitHub Desktop.
Represents a reference type that may never be assigned a value of null.
This file contains hidden or 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 T mValue; | |
public T Value | |
{ | |
get { return this.mValue; } | |
set | |
{ | |
if( value == null ) | |
throw new ArgumentNullException( "value" ); | |
this.mValue = value; | |
} | |
} | |
// Prior to C# 6.0, structs were not allowed to contain user-defined, | |
// parameterless constructors. Remove the preprocessor directive | |
// or define 'CSHARP6' in your preferred way to enable this constructor. | |
#if CSHARP6 | |
public NotNull() | |
{ | |
throw new InvalidOperationException( "NotNull must be initialized with a value." ); | |
} | |
#endif | |
public NotNull( T value ) | |
{ | |
Value = value; | |
} | |
public static implicit operator T( NotNull<T> instance ) | |
{ | |
return instance.Value; | |
} | |
public static implicit operator NotNull<T>( T value ) | |
{ | |
return new NotNull<T>( value ); | |
} | |
public override string ToString() | |
{ | |
return this.Value.ToString(); | |
} | |
public static bool operator ==( NotNull<T> left, T right ) | |
{ | |
return right == null ? false : left.Equals( right ); | |
} | |
public static bool operator !=( NotNull<T> left, T right ) | |
{ | |
return !( left == right ); | |
} | |
public override bool Equals( object other ) | |
{ | |
if( other == null ) | |
return false; | |
if( other is NotNull<T> ) | |
return this.Equals( (NotNull<T>)other ); | |
if( other is T ) | |
return this.Equals( (T)other ); | |
return false; | |
} | |
public bool Equals( NotNull<T> other ) | |
{ | |
return this.Value.Equals( other.Value ); | |
} | |
public override int GetHashCode() | |
{ | |
return this.Value.GetHashCode(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment