Constant<T>
Allows to use constant values as generic parameters.
using DotNext.Runtime.CompilerServices;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace DotNext.Generic
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public abstract class Constant<[System.Runtime.CompilerServices.Nullable(2)] T> : ISupplier<T>, IFunctional<Func<T>>
{
public T Value { get; }
protected Constant(T constVal)
{
Value = constVal;
}
T ISupplier<T>.Invoke()
{
return Value;
}
public sealed override string ToString()
{
T value = Value;
return value?.ToString() ?? "NULL";
}
public sealed override int GetHashCode()
{
T value = Value;
return value?.GetHashCode() ?? 0;
}
[System.Runtime.CompilerServices.NullableContext(2)]
public sealed override bool Equals([NotNullWhen(true)] object other)
{
if (!(other is T)) {
Constant<T> constant = other as Constant<T>;
if (constant != null)
return object.Equals(Value, constant.Value);
return false;
}
T val = (T)other;
return object.Equals(val, Value);
}
public static implicit operator T([System.Runtime.CompilerServices.Nullable(new byte[] {
2,
1
})] Constant<T> const)
{
if (const != null)
return const.Value;
return default(T);
}
}
}