Do not ignore method results
TypeName |
DoNotIgnoreMethodResults |
CheckId |
CA1806 |
Category |
Microsoft.Performance |
Breaking Change |
NonBreaking |
Cause
A constructor or method is called that creates and returns a new object, and the new object is neither used nor assigned to a variable.
Rule Description
Unnecessary object creation and the associated garbage collection of the unused object degrade performance.
How to Fix Violations
To fix a violation of this rule, use the new object or remove the method or constructor call.
When to Exclude Warnings
Do not exclude a warning from this rule unless the act of creating the object serves some purpose.
Example
The following example shows a class that ignores the result of calling String.Trim.
Imports System
Imports System.Globalization
Namespace PerformanceLibrary
Public Class IgnoredMethodResults
Sub Violations()
Dim violationOne As String = "lo"
Dim violationTwo As String = "MediuM "
violationOne.ToUpper(CultureInfo.InvariantCulture)
violationTwo.ToLower(CultureInfo.InvariantCulture).Trim()
End Sub
End Class
End Namespace
using System;
using System.Globalization;
namespace PerformanceLibrary
{
public class IgnoredMethodResults
{
public void Violations()
{
"violationOne".ToUpper(CultureInfo.InvariantCulture);
string violationTwo = "MediuM ";
violationTwo.ToLower(CultureInfo.InvariantCulture).Trim();
new Random();
}
}
}
The following example fixes the above violation by assigning the result of String.Trim back to the variable it was called on.
The following example shows a method that does not use an object that it creates.
Note |
---|
This violation cannot be reproduced in Visual Basic. |
The following example fixes the above violation by removing the unnecessary creation of an object.