Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Operator <= cannot be applied to operands of type TKey

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading