Search code examples
c#roslyn-code-analysisimmutable-collections

How to show "CA1806: Do not ignore method results" for ImmutableList<T>.Add?


Is there a way to show a warning when you call ImmutableList<T>.Add but don't use its result?

I thought CA1806 would do that, and it does for some methods that return results (like string.ToUpper() from the screenshot), but not for ImmutableList<T>.Add.

enter image description here


Solution

  • According to the help page for CA1806, the cause of this:

    There are several possible reasons for this warning:

    • A new object is created but never used.
    • A method that creates and returns a new string is called and the new string is never used.
    • A COM or P/Invoke method that returns a HRESULT or error code that's never used.
    • A language-integrated query (LINQ) method that returns a result that's never used.

    Note that it only says "a method that creates and returns a new string". It is possible that the analyser only looks for string methods as the default behaviour. It doesn't "know" that ImmutableList<T>.Add also returns a new instance that should be used.

    As is said in the bottom of that page, you can add more methods that trigger CA1806 by adding the method to the .editorconfig option dotnet_code_quality.CA1806.additional_use_results_methods. This is a | separated list of method names.

    dotnet_code_quality.CA1806.additional_use_results_methods = M:System.Collections.Immutable.ImmutableList`1.Add(`0)
    

    Notice the unusual syntax for referring to the method. You can see how this format works here.