Skip to content

Instantly share code, notes, and snippets.

@tatelax
Last active September 22, 2021 17:43
Show Gist options
  • Save tatelax/fa43f17d33f76571e55146cd90b7edbd to your computer and use it in GitHub Desktop.
Save tatelax/fa43f17d33f76571e55146cd90b7edbd to your computer and use it in GitHub Desktop.
fholm's Option<T>
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public struct Option<T> : IEquatable<Option<T>> {
T _value;
bool _hasValue;
public T Value {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _hasValue ? _value : ThrowInvalidOperationException();
}
public bool IsSome {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _hasValue;
}
public bool IsNone {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _hasValue == false;
}
public Option(T value) {
_value = value;
_hasValue = true;
}
static T ThrowInvalidOperationException() {
throw new InvalidOperationException();
}
public static Option<T> None {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => default;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator Option<T>(T value) {
return new Option<T>(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Deconstruct(out T value) {
value = Value;
}
public bool Equals(Option<T> other) {
return _hasValue == other._hasValue && EqualityComparer<T>.Default.Equals(_value, other._value);
}
public override bool Equals(object obj) {
return obj is Option<T> other && Equals(other);
}
public override int GetHashCode() {
unchecked {
return (EqualityComparer<T>.Default.GetHashCode(_value) * 397) ^ _hasValue.GetHashCode();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment