Created
February 28, 2012 07:41
-
-
Save rofr/1930423 to your computer and use it in GitHub Desktop.
NonNullable example
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
// NonNullable, the logical inverse of Nullable. Prevents a reference type from being null. | |
// Implicit conversions to and from the wrapped type provide transparency. | |
// Usage: Wrap method arguments and/or return values with NonNullable | |
// | |
public struct NonNullable<T> where T : class | |
{ | |
public readonly T Item; | |
public NonNullable(T item) | |
{ | |
if (item == null) throw new ArgumentNullException(); | |
Item = item; | |
} | |
public static implicit operator T(NonNullable<T> n) | |
{ | |
return n.Item; | |
} | |
public static implicit operator NonNullable<T>(T item) | |
{ | |
return new NonNullable<T>(item); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Foo("NOT NULL"); | |
string s = SafeReference(); //throws | |
Foo(null); //throws | |
} | |
static NonNullable<String> SafeReference() | |
{ | |
return null; | |
} | |
static void Foo(NonNullable<String> name) | |
{ | |
string safeReference = name; | |
Console.WriteLine(safeReference.ToLower()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Disclaimer: This is just a proof of concept exercise. I don't use this pattern.