Maybe.cs 1.0 KB

123456789101112131415161718192021222324252627
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. namespace System.Linq
  6. {
  7. internal readonly struct Maybe<T> : IEquatable<Maybe<T>>
  8. {
  9. public Maybe(T value)
  10. {
  11. HasValue = true;
  12. Value = value;
  13. }
  14. public bool HasValue { get; }
  15. public T Value { get; }
  16. public bool Equals(Maybe<T> other) => HasValue == other.HasValue && EqualityComparer<T>.Default.Equals(Value, other.Value);
  17. public override bool Equals(object? other) => other is Maybe<T> m && Equals(m);
  18. public override int GetHashCode() => HasValue ? EqualityComparer<T>.Default.GetHashCode(Value!) : 0;
  19. public static bool operator ==(Maybe<T> first, Maybe<T> second) => first.Equals(second);
  20. public static bool operator !=(Maybe<T> first, Maybe<T> second) => !first.Equals(second);
  21. }
  22. }