Operator <= cannot be applied to operands of type TKey

Viewed 90

arg <= default(TKey) produces

Operator <= cannot be applied to operands of type TKey.

public class ParameterIdValidator<TKey> : IEndpointFilter
    where TKey : IEquatable<TKey>
{

    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        Type type = typeof(TKey);

        var arg = context.GetArgument<TKey>(0);    

        if
        (
            type == typeof(short) ||
            type == typeof(ushort) ||
            type == typeof(int) ||
            type == typeof(uint) ||
            type == typeof(long) ||
            type == typeof(ulong)
        )
        {    
            if (arg <= default(TKey))
            {
                return Results.BadRequest("Id must be positive!");
            }   
        }

        return await next(context);
    }
}

How to fix this problem?

1 Answers

The simplest approach would be to use IComparable<>, in my view:

if (arg is IComparable<TKey> key && 
    default(TKey) != null && // Protect against string, for example
    key.CompareTo(default(TKey)) <= 0)
{
    return Results.BadRequest("Id must be positive!");
}

You could remove the middle condition if you restricted TKey to be a value type, with where TKey : struct.

(In C# 11 there will be some more options here, but this seems like the simplest approach before then.)

Related