Skip to content

Commit 02833be

Browse files
committed
BUGFIX IDISP003 when assitgned in ctor expression body.
Fix #183.
1 parent 788cda7 commit 02833be

3 files changed

Lines changed: 29 additions & 2 deletions

File tree

IDisposableAnalyzers.Test/IDISP003DisposeBeforeReassigningTests/Valid.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1308,5 +1308,25 @@ protected virtual void Dispose(bool disposing)
13081308

13091309
RoslynAssert.Valid(Analyzer, code);
13101310
}
1311+
1312+
[Test]
1313+
public static void AssigningFieldInExpressionBodyCtor()
1314+
{
1315+
var code = @"
1316+
namespace N
1317+
{
1318+
using System;
1319+
using System.Threading;
1320+
1321+
public class C
1322+
{
1323+
private readonly IDisposable disposable;
1324+
1325+
public C()=> this.disposable = new CancellationTokenSource();
1326+
}
1327+
}";
1328+
1329+
RoslynAssert.Valid(Analyzer, code);
1330+
}
13111331
}
13121332
}

IDisposableAnalyzers/Helpers/Disposable.IsCreation.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ internal static Result IsAlreadyAssignedWithCreated(ExpressionSyntax disposable,
1717
return Result.No;
1818
}
1919

20+
if (disposable is { Parent: AssignmentExpressionSyntax { Parent: ArrowExpressionClauseSyntax { Parent: ConstructorDeclarationSyntax _} } })
21+
{
22+
assignedSymbol = null;
23+
return Result.No;
24+
}
25+
2026
var symbol = semanticModel.GetSymbolSafe(disposable, cancellationToken);
2127
if (symbol is null)
2228
{

IDisposableAnalyzers/Helpers/Walkers/DisposableWalker.Returns.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.Threading;
44
using Gu.Roslyn.AnalyzerExtensions;
55
using Microsoft.CodeAnalysis;
6+
using Microsoft.CodeAnalysis.CSharp;
67
using Microsoft.CodeAnalysis.CSharp.Syntax;
78

89
internal sealed partial class DisposableWalker
@@ -48,8 +49,8 @@ private static bool Returns(ExpressionSyntax candidate, Recursion recursion)
4849
{
4950
{ Parent: ReturnStatementSyntax _ }
5051
=> true,
51-
{ Parent: ArrowExpressionClauseSyntax _ }
52-
=> true,
52+
{ Parent: ArrowExpressionClauseSyntax { Parent: { } parent } }
53+
=> !parent.IsKind(SyntaxKind.ConstructorDeclaration),
5354
{ Parent: EqualsValueClauseSyntax { Parent: VariableDeclaratorSyntax variableDeclarator } }
5455
=> recursion.Target(variableDeclarator) is { } target &&
5556
Returns(target, recursion),

0 commit comments

Comments
 (0)