Why is CS0472 just a warning?

Heiko 1,286 Reputation points
2025-01-24T17:46:53.5733333+00:00

I found a warning CS0472 from the C# compiler. I have this in my code:

List<string> list = GetList();

if (list.Count == null) // CS0472
DoA();
else
DoB();

Why is it just a warning? IntelliSense tells me that this expression is always false. The code is not doing the right thing.

Why does it make sense to treat it as a warning?

https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0472

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,244 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,476 Reputation points
    2025-01-26T10:24:15.1+00:00

    Rather than checking for null, check count, as the rule of thumb is not to return null but an empty list, in this case.

    For example, depending on the day of the week, return a list of two items or an empty list. The code was written with NET Core 9.

    internal static class DateTimeExtensions
    {
        public static bool IsWeekend(this DateTime self)
            => self.DayOfWeek is DayOfWeek.Sunday or DayOfWeek.Saturday;
    }
    .
    .
    .
    private static List<string> GetList() 
        => DateTime.Now.IsWeekend() ? ["item 1", "item 2"] : [];
    .
    .
    .
    List<string> list = GetList();
    if (list.Count == 0)
    {
        // Handle the case where the list is empty
    }
    

  2. Heiko 1,286 Reputation points
    2025-01-27T11:32:33.28+00:00

    I have found an answer: If we had a generic method, the query of a variable of type T would have to be valid:

    void DoSmth<T>(T smth)
    {
    if (smth == null)
    //...
    }

    The compiler must therefore allow this comparison, in my case also of type int:

    if (list.Count == null)

    But for expressions with non-generic value types, a comparison with null is never intended.

    So I have specified in the project settings that CS0472 must be treated as an error.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.