Generic not-null validator for CA1062 in .NET 6

41 Views Asked by At

I have a generic method that ensures an IEnumerable is not null or empty.

public static void IsNotNullOrEmpty<T>(IEnumerable<T> enumerable)
{
    if (enumerable == null || !enumerable.Any())
        throw new Exception();
}

In .editorconfig, I'd like to register this method as a not-null validator for code analysis by setting dotnet_code_quality.CA1062.null_check_validation_methods. For non-generic methods, I can set this to:

dotnet_code_quality.CA1062.null_check_validation_methods = Namespace.Class.Method(ParameterType)

How is this done for generic validators?

1

There are 1 best solutions below

0
Mad hatter On

I know this will not answer completely your question, it would be only a workaround, but what about removing genericity from your method ?

public static void IsNotNullOrEmpty(IEnumerable enumerable)
{
    if (enumerable == null)
        throw new Exception();

    var iterator = enumerable.GetEnumerator();
    var empty = !iterator.MoveNext();

    if (empty)
        throw new Exception();
}