Files
spark/src/cs/Bts.Core/Optional.cs
T
John Colvin e7bd57964e refactor: Rename Optional members PascalCase
Also reformat code according to new style guidlines
2026-03-08 16:00:50 +00:00

64 lines
1.7 KiB
C#

namespace Spark.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
public readonly struct Optional<T> : IEquatable<Optional<T>>, IEquatable<T> {
readonly T? value;
public Optional(T value) {
this.value = value;
HasValue = true;
}
public static Optional<T> Empty => default;
[MemberNotNullWhen(true, nameof(value))]
public bool HasValue { get; }
public T Value => HasValue
? value
: throw new InvalidOperationException("Value not set");
public T GetValueOrDefault(T defaultValue) =>
HasValue
? Value
: defaultValue;
public bool Equals(Optional<T> other) =>
HasValue == other.HasValue &&
(!HasValue || EqualityComparer<T>.Default.Equals(Value, other.Value));
public bool Equals(T? other) =>
HasValue && EqualityComparer<T>.Default.Equals(Value, other);
public override bool Equals(object? obj) =>
obj is Optional<T> other
? Equals(other)
: obj is T otherVal && Equals(otherVal);
public override int GetHashCode() =>
HasValue
? Value?.GetHashCode() ?? throw new InvalidOperationException()
: 0;
public override string? ToString() =>
HasValue
? Value?.ToString()
: string.Empty;
public static implicit operator Optional<T>(T value) =>
new(value);
[return: MaybeNull]
public static implicit operator T(Optional<T> optional) =>
optional.Value;
public static bool operator ==(Optional<T> left, Optional<T> right) =>
left.Equals(right);
public static bool operator !=(Optional<T> left, Optional<T> right) =>
!(left == right);
}