This repository has been archived on 2025-10-24. You can view files and clone it, but cannot push or open issues or pull requests.
Files
nub-lang-archive-2/src/common/Optional.cs
2025-06-12 23:57:59 +02:00

77 lines
1.6 KiB
C#

using System.Diagnostics.CodeAnalysis;
namespace Nub.Lang.Common;
public readonly struct Optional
{
public static Optional<TValue> Empty<TValue>() => new();
/// <summary>
/// Alias for creating an Optional&lt;TValue&gt; which allows for implicit types
/// </summary>
/// <param name="value"></param>
/// <typeparam name="TValue"></typeparam>
/// <returns></returns>
public static Optional<TValue> OfNullable<TValue>(TValue? value)
{
return value ?? Optional<TValue>.Empty();
}
}
public readonly struct Optional<TValue>
{
public static Optional<TValue> Empty() => new();
public static Optional<TValue> OfNullable(TValue? value)
{
return value ?? Empty();
}
public Optional()
{
Value = default;
HasValue = false;
}
public Optional(TValue value)
{
Value = value;
HasValue = true;
}
public TValue? Value { get; }
[MemberNotNullWhen(true, nameof(Value))]
public bool HasValue { get; }
[MemberNotNullWhen(true, nameof(Value))]
public bool TryGetValue([NotNullWhen(true)] out TValue? value)
{
if (HasValue)
{
value = Value;
return true;
}
value = default;
return false;
}
public TValue GetValue()
{
return Value ?? throw new InvalidOperationException("Value is not set");
}
public static implicit operator Optional<TValue>(TValue value) => new(value);
public TValue Or(TValue other)
{
if (HasValue)
{
return Value;
}
return other;
}
}