Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NullChecking {
struct NonNull<T>
where T : class
public readonly T Value;
public NonNull(T value) {
if (value == null) {
string message = string.Format("Value cannot be null for parameter with type 'NonNull<{0}>'.", typeof(T).Name);
throw new ArgumentNullException("value", message);
this.Value = value;
public static implicit operator T(NonNull<T> nonNullWrapper) {
return nonNullWrapper.Value;
public static implicit operator NonNull<T>(T value) {
return new NonNull<T>(value);
struct NonNull {
public static void Use<TArgument>(NonNull<TArgument> arg, Action<TArgument> action)
where TArgument: class
class Program {
static void Main(string[] args) {
// Print2(null);
static void Print(string foo) {
Console.WriteLine("foo length: {0}", foo.Length);
static void Print2(NonNull<string> foo) {
//NonNull.Use(foo, f => {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment