Skip to content
This repository has been archived by the owner on Oct 12, 2022. It is now read-only.

Commit

Permalink
Merge pull request #64 from edespong/forech_string
Browse files Browse the repository at this point in the history
Issue #63 - Do not warn on foreach over string
  • Loading branch information
Mukul Sabharwal authored Nov 25, 2018
2 parents 8911358 + 913c430 commit 01c6dd2
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -119,5 +119,16 @@ private IEnumerator<int> GetIEnumeratorViaIEnumerable()
// Diagnostic: (11,35): warning HeapAnalyzerEnumeratorAllocationRule: Non-ValueType enumerator may result in a heap allocation ***
AssertEx.ContainsDiagnostic(info.Allocations, id: EnumeratorAllocationAnalyzer.ReferenceTypeEnumeratorRule.Id, line: 11, character: 35);
}

[TestMethod]
public void EnumeratorAllocation_IterateOverString_NoWarning()
{
var sampleProgram = "foreach (char c in \"foo\") { }";

var analyser = new EnumeratorAllocationAnalyzer();
var info = ProcessCode(analyser, sampleProgram, ImmutableArray.Create(SyntaxKind.ForEachStatement));

Assert.AreEqual(0, info.Allocations.Count);
}
}
}
7 changes: 7 additions & 0 deletions ClrHeapAllocationsAnalyzer/EnumeratorAllocationAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ protected override void AnalyzeNode(SyntaxNodeAnalysisContext context)
if (typeInfo.Type == null)
return;

if (typeInfo.Type.Name == "String" && typeInfo.Type.ContainingNamespace.Name == "System")
{
// Special case for System.String which is optmizined by
// the compiler and does not result in an allocation.
return;
}

// Regular way of getting the enumerator
ImmutableArray<ISymbol> enumerator = typeInfo.Type.GetMembers("GetEnumerator");
if ((enumerator == null || enumerator.Length == 0) && typeInfo.ConvertedType != null)
Expand Down

0 comments on commit 01c6dd2

Please sign in to comment.