Skip to content

Instantly share code, notes, and snippets.

@Boggin Boggin/avoidNull.csx
Created Jul 26, 2016

Embed
What would you like to do?
public struct Option<T>
{
private readonly T _value;
public T Value
{
get
{
if (!HasValue)
throw new InvalidOperationException();
return _value;
}
}
public bool HasValue
{
get { return _value != null; }
}
public Option(T value)
{
_value = value;
}
public static implicit operator Option<T>(T value)
{
return new Option<T>(value);
}
}
public class User
{
public int Id;
public string Name;
}
public Option<User> GetUser(int id)
{
var users = new List<User>
{
new User { Id = 1, Name = "Joe Bloggs" },
new User { Id = 2, Name = "John Smith" }
};
var u = users.FirstOrDefault(user => user.Id == id);
return u != null ? new Option<User>(u) : new Option<User>();
}
var maybeUser = GetUser(2);
var username = maybeUser.HasValue ? maybeUser.Value.Name : string.Empty;
System.Console.WriteLine("username: " + username);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.