Skip to content

Commit aeac552

Browse files
committed
Exclude constructor initializers from SA1101
1 parent 9950efe commit aeac552

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

StyleCop.Analyzers/StyleCop.Analyzers.Test/ReadabilityRules/SA1101UnitTests.cs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,41 @@ public class Foo
363363
{
364364
public string Array { get; } = nameof(Array);
365365
}
366+
";
367+
368+
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
369+
}
370+
371+
[Fact]
372+
[WorkItem(2799, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2799")]
373+
public async Task TestNameofInConstructorCallAsync()
374+
{
375+
var testCode = @"
376+
public class TestClass
377+
{
378+
public TestClass()
379+
: this(nameof(P))
380+
{
381+
}
382+
383+
public TestClass(string p)
384+
{
385+
this.P = p;
386+
}
387+
388+
public string P { get; }
389+
}
390+
391+
public class DerivedTestClass : TestClass
392+
{
393+
public DerivedTestClass()
394+
: base(nameof(Q))
395+
{
396+
this.Q = string.Empty;
397+
}
398+
399+
public string Q { get; }
400+
}
366401
";
367402

368403
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);

StyleCop.Analyzers/StyleCop.Analyzers/ReadabilityRules/SA1101PrefixLocalCallsWithThis.cs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,10 @@ private static void HandleSimpleName(SyntaxNodeAnalysisContext context)
124124

125125
break;
126126

127+
case SyntaxKind.Argument when IsPartOfConstructorInitializer((SimpleNameSyntax)context.Node):
128+
// constructor invocations cannot contain this.
129+
return;
130+
127131
default:
128132
break;
129133
}
@@ -264,5 +268,20 @@ private static bool HasThis(SyntaxNode node)
264268

265269
return false;
266270
}
271+
272+
private static bool IsPartOfConstructorInitializer(SyntaxNode node)
273+
{
274+
for (; node != null; node = node.Parent)
275+
{
276+
switch (node.Kind())
277+
{
278+
case SyntaxKind.ThisConstructorInitializer:
279+
case SyntaxKind.BaseConstructorInitializer:
280+
return true;
281+
}
282+
}
283+
284+
return false;
285+
}
267286
}
268287
}

0 commit comments

Comments
 (0)