Skip to content

Instantly share code, notes, and snippets.

@Boggin
Created July 26, 2016 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Boggin/d53660f32aeaa35e0b028919ddc465e3 to your computer and use it in GitHub Desktop.
Save Boggin/d53660f32aeaa35e0b028919ddc465e3 to your computer and use it in GitHub Desktop.
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