Skip to content

Commit 6c2f6b9

Browse files
committed
IDISP004 when yield return.
Fix #215
1 parent b72e7e7 commit 6c2f6b9

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

IDisposableAnalyzers.Test/IDISP004DoNotIgnoreCreatedTests/Valid.Returned.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,5 +475,26 @@ public class C
475475
}".AssertReplace("new CompositeDisposable(File.OpenRead(fileName))", expression);
476476
RoslynAssert.Valid(Analyzer, code);
477477
}
478+
479+
[Test]
480+
public static void YieldReturnFileOpenRead()
481+
{
482+
var code = @"
483+
namespace N
484+
{
485+
using System;
486+
using System.Collections.Generic;
487+
using System.IO;
488+
489+
class C
490+
{
491+
IEnumerable<IDisposable> M()
492+
{
493+
yield return File.OpenRead(string.Empty);
494+
}
495+
}
496+
}";
497+
RoslynAssert.Valid(Analyzer, code);
498+
}
478499
}
479500
}

IDisposableAnalyzers/Helpers/Disposable.Returns.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ private static bool Returns(ExpressionSyntax candidate, Recursion recursion)
4949
{
5050
{ Parent: ReturnStatementSyntax _ }
5151
=> true,
52+
{ Parent: YieldStatementSyntax _ }
53+
=> true,
5254
{ Parent: ArrowExpressionClauseSyntax { Parent: { } parent } }
5355
=> !parent.IsKind(SyntaxKind.ConstructorDeclaration),
5456
{ Parent: MemberAccessExpressionSyntax { Parent: InvocationExpressionSyntax invocation } }

ValidCode/Returned.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
namespace ValidCode
2+
{
3+
using System;
4+
using System.Collections.Generic;
5+
using System.IO;
6+
using System.Linq;
7+
8+
class Returned
9+
{
10+
void Consume()
11+
{
12+
using var fileOpenReadProperty = this.FileOpenReadProperty;
13+
using var fileOpenRead = this.FileOpenRead();
14+
using var yieldReturnFileOpenRead = this.YieldReturnFileOpenRead().Single();
15+
}
16+
17+
#pragma warning disable IDISP012 // Property should not return created disposable.
18+
IDisposable FileOpenReadProperty => File.OpenRead(string.Empty);
19+
#pragma warning restore IDISP012 // Property should not return created disposable.
20+
21+
IDisposable FileOpenRead() => File.OpenRead(string.Empty);
22+
23+
IEnumerable<IDisposable> YieldReturnFileOpenRead()
24+
{
25+
yield return File.OpenRead(string.Empty);
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)