Do not ignore method results
Do not ignore method results
Microsoft docsDescription
Unnecessary object creation and the associated garbage collection of the unused object degrade performance.
Strings are immutable and methods such as System.String.ToUpper return a new instance of a string instead of modifying the instance of the string in the calling method.
Ignoring HRESULT or an error code can lead to low-resource conditions or unexpected behavior in error conditions.
LINQ methods and methods annotated with System.Diagnostics.Contracts.PureAttribute are known to not have side effects, and the result should not be ignored.
Cause
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 returns a
HRESULTor error code that's never used. - A language-integrated query (LINQ) method returns a result that's never used.
- A
[Pure]method is called and the return value is never used.
How to fix violations
If a method creates a new instance of an object that's never used, pass the instance as an argument to another method or assign the instance to a variable. If the object creation is unnecessary, remove it.
-or-
If method A calls method B but does not use the new string instance that method B returns, pass the instance as an argument to another method or assign the instance to a variable. Or remove the call if it's unnecessary.
-or-
If method A calls method B but does not use the HRESULT or error code that the method returns, use the result in a conditional statement, assign the result to a variable, or pass it as an argument to another method.
-or-
If method A calls a LINQ or pure method B but does not use the result, use the result in a conditional statement, assign the result to a variable, or pass it as an argument to another method.
Example
#pragma warning disable CA1806
// The code that's violating the rule is on this line.
#pragma warning restore CA1806When to suppress
Do not suppress a warning from this rule unless the act of creating the object serves some purpose.