Last active
November 6, 2015 12:40
-
-
Save BlythMeister/025e89c3ffd504b0cf3b to your computer and use it in GitHub Desktop.
Some/None
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
using System; | |
namespace OptionTypes | |
{ | |
public abstract class Option<T> | |
{ | |
public abstract T GetSome { get; } | |
public abstract override string ToString(); | |
protected T Value; | |
public bool IsSome { get; protected set; } | |
public bool IsNone { get { return !IsSome; } } | |
public static Some<T> Some(T value) | |
{ | |
return new Some<T>(value); | |
} | |
public static None<T> None() | |
{ | |
return new None<T>(); | |
} | |
} | |
public sealed class Some<T> : Option<T> | |
{ | |
public Some(T value) | |
{ | |
if (value == null) | |
throw new ArgumentNullException("value", "Argument passed to Some was null - use None<T> instead."); | |
Value = value; | |
IsSome = true; | |
} | |
public override T GetSome { get { return Value; } } | |
public override string ToString() | |
{ | |
return Value.ToString(); | |
} | |
} | |
public sealed class None<T> : Option<T> | |
{ | |
public None() | |
{ | |
IsSome = false; | |
} | |
public override T GetSome { get { throw new InvalidOperationException("No value on None<T>"); } } | |
public override string ToString() | |
{ | |
return "None"; | |
} | |
} | |
public class MyClass | |
{ | |
public void Main() | |
{ | |
var some = Option<string>.Some("Hello"); | |
var none = Option<string>.None(); | |
WriteDataIf(some); | |
WriteDataIf(none); | |
WriteDataSwitch(some); | |
WriteDataSwitch(none); | |
} | |
private void WriteDataIf(Option<string> option) | |
{ | |
if (option.IsSome) | |
{ | |
Console.WriteLine(option.GetSome); | |
} | |
else | |
{ | |
Console.WriteLine("Its None"); | |
} | |
} | |
private void WriteDataSwitch(Option<string> option) | |
{ | |
switch(option.IsSome) | |
{ | |
case true: | |
Console.WriteLine(option.GetSome); | |
break; | |
default: | |
Console.WriteLine("Its None"); | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment