Skip to content

Instantly share code, notes, and snippets.

@rofr
Created February 28, 2012 07:41
Show Gist options
  • Save rofr/1930423 to your computer and use it in GitHub Desktop.
Save rofr/1930423 to your computer and use it in GitHub Desktop.
NonNullable example
// 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());
}
}
@rofr
Copy link
Author

rofr commented Feb 28, 2012

Disclaimer: This is just a proof of concept exercise. I don't use this pattern.

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