Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save miklund/5770d9cef25aba81552b to your computer and use it in GitHub Desktop.
Save miklund/5770d9cef25aba81552b to your computer and use it in GitHub Desktop.
2011-04-08 Option type implementation in C#
# Title: Option type implementation in C#
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2011/04/08/option-type-implementation-in-csharp.html
public Option<User> FindUserByName(string name)
{
var query = from user in Users
where user.FirstName.Contains(name) || user.Surname.Contains(name)
select user;
var found = query.FirstOrDefault();
if (found == null)
return new None<User>();
return new Some<User>(found);
}
public Option<int> GetIndexOfSubstring(string s, string substring)
{
var index = s.IndexOf(substring);
if (index == -1)
return new None<int>();
return new Some<int>(index);
}
let getIndexOfSubstring (s : string) (substring : string) =
let index = s.IndexOf(substring)
match index with
| -1 -> None
| n -> Some n
// Used as return type from method
public abstract class Option<T>
{
// Could contain the value if Some, but not if None
public abstract T Value { get; }
public abstract bool IsSome { get; }
public abstract bool IsNone { get; }
}
public static class OptionExtensions
{
public static Option<T> SomeOrNone<T>(this T reference)
where T : class
{
if (reference == null) return new None<T>();
return new Some<T>(reference);
}
}
public sealed class Some : Option
{
private T value;
public Some(T value)
{
// Setting Some to null, nullifies the purpose of Some/None
if (value == null)
{
throw new System.ArgumentNullException("value", "Some value was null, use None instead");
}
this.value = value;
}
public override T Value { get { return value; } }
public override bool IsSome { get { return true; } }
public override bool IsNone { get { return false; } }
}
public sealed class None : Option
{
public override T Value
{
get { throw new System.NotSupportedException("There is no value"); }
}
public override bool IsSome { get { return false; } }
public override bool IsNone { get { return true; } }
}
// Get string before substring
private string SubstringBefore(string s, string substring)
{
var operations = new StringOperations();
var index = operations.GetIndexOfSubstring(s, substring);
if (index.IsSome)
return s.Substring(0, index.Value);
return s;
}
[Test]
public void ShouldReturnSomeIndexForExistingSubstring()
{
/* Test implementation */
}
[Test]
public void ShouldReturnNoneWhenSubstringDoesNotExist()
{
/* Test implementation */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment