Skip to content

Instantly share code, notes, and snippets.

@sefacan
Created February 27, 2022 00:48
Show Gist options
  • Save sefacan/4b9872111b48f977c5dc77115a2497f4 to your computer and use it in GitHub Desktop.
Save sefacan/4b9872111b48f977c5dc77115a2497f4 to your computer and use it in GitHub Desktop.
public class CollectionUtils
{
public static bool AreEquals<T>(IEnumerable<T> items, IEnumerable<T> otherItems)
{
return new HashSet<T>(items)
.SetEquals(otherItems);
}
public static bool IsEmpty(IEnumerable items) => items == null || !items.GetEnumerator().MoveNext();
public static bool IsNotEmpty(IEnumerable items) => !IsEmpty(items);
}
public class ObjectUtils
{
public static T RequireNonNull<T>(T obj) {
if (obj == null)
throw new NullReferenceException();
return obj;
}
public static T RequireNonNull<T>(T obj, string message) {
if (obj == null)
throw new NullReferenceException(message);
return obj;
}
public static bool IsNull(object obj) {
return obj == null;
}
public static bool NonNull(object obj) {
return obj != null;
}
public static T RequireNonNullElse<T>(T obj, T defaultObj) {
return (obj != null) ? obj : RequireNonNull(defaultObj, "defaultObj");
}
}
public sealed class Optional<T>
{
private static readonly Optional<T> empty = new();
private readonly T _value;
private Optional() => _value = default;
private Optional(T value)
{
if (IsEmpty())
throw new NullReferenceException();
_value = value;
}
public static Optional<T> Empty() => empty;
public static Optional<T> Of(T value) => new(value);
public static Optional<T> OfNullable(T value) => value == null ? Empty() : Of(value);
public static Optional<T> OfNullable(Func<T> func) => func != null ? Of(func()) : Empty();
public bool HasValue => _value != null;
public T Get() => _value == null ? throw new NullReferenceException() : _value;
public bool IsEmpty() => _value == null;
public T OrElse(T other) => HasValue ? _value : other;
public T OrElseGet(Func<T> getOther) => HasValue ? _value : getOther();
public T OrElseThrow<E>(Func<E> exception) where E : Exception => HasValue ? _value : throw exception();
public static explicit operator T(Optional<T> optional) => OfNullable((T)optional).Get();
public static implicit operator Optional<T>(T optional) => OfNullable(optional);
public override bool Equals(object obj)
{
if (obj is Optional<T>) return true;
if (!(obj is Optional<T>)) return false;
return Equals(_value, (obj as Optional<T>)._value);
}
public override int GetHashCode() => _value.GetHashCode();
public override string ToString() =>
HasValue ? $"Optional has <{_value}>" : $"Optional has no value: <{_value}>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment