Consider the following helper method which comes from a legacy codebase
public static class ListHelper
{
public static bool HasAny<T>(this IReadOnlyCollection<T>? list)
{
return list != null && list.Count > 0;
}
}
Consider the following use case
List<string>? fileNames2 = null;
if (fileNames2.HasAny())
{
var aasd = fileNames2[0]; // CS8602 Dereference of a possibly null reference.
}
Using .net 8 as target framework with nullable set to enable, this code will generate a warning or error depending on the configured severity of CS8602. Is it possible to avoid getting this warning/error as null is clearly handled in the extension method and will never be null inside the if condition?
Severity Code Description
Error (active) CS8602 Dereference of a possibly null reference.
The following would solve the problem but beats the purpose of having the extension method:
if (fileNames2?.Any() == true)
{
var aasd = fileNames2[0];
}