Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions documentation/SA1202.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ To comply with this rule, adjacent elements of the same type should be positione
* private protected
* private

:memo: Static constructors and explicitly implemented interface members are considered *public* for the purposes of this
rule.
:memo: Static constructors and explicitly implemented interface methods, properties, indexers, and events are considered
*public* for the purposes of this rule. Explicit interface events were treated as private by StyleCop Classic; treating
them as public here is intentional and consistent with the other explicit interface members.

Complying with a standard ordering scheme based on access level can increase the readability and maintainability of the
file and make it easier to identify the public interface that is being exposed from a class.
Expand Down
5 changes: 3 additions & 2 deletions documentation/cs-cz/SA1202.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ pořadí:
* private protected
* private

:memo: Pro účely tohoto pravidla se statické konstruktory a explicitně implementované členy rozhraní považují za
*public*.
:memo: Pro účely tohoto pravidla se statické konstruktory a explicitně implementované metody, vlastnosti, indexery a
události rozhraní považují za *public*. Ve StyleCop Classic byly explicitně implementované události rozhraní považovány
za *private*; zde se záměrně považují za *public*, stejně jako ostatní explicitně implementované členy rozhraní.

Dodržování standardního schématu řazení podle úrovně přístupu může zvýšit čitelnost a udržovatelnost souboru a usnadnit
rozpoznání veřejného rozhraní, které třída zpřístupňuje.
Expand Down
4 changes: 3 additions & 1 deletion documentation/ru-ru/SA1202.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@
* private protected
* private

:memo: Для целей этого правила статические конструкторы и явно реализованные члены интерфейса считаются *public*.
:memo: Для целей этого правила статические конструкторы и явно реализованные методы, свойства, индексаторы и события
интерфейса считаются *public*. В StyleCop Classic явно реализованные события интерфейса считались *private*; здесь они
намеренно считаются *public*, как и другие явно реализованные члены интерфейса.

Соблюдение стандартного порядка по уровню доступа повышает читаемость и удобство сопровождения файла, а также помогает быстрее определить открытый интерфейс класса.

Expand Down
3 changes: 2 additions & 1 deletion src/StyleCop.Analyzers/Helpers/MemberOrderHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,8 @@ internal static AccessLevel GetAccessLevelForOrdering(SyntaxNode member, SyntaxT
if ((type == SyntaxKind.ConstructorDeclaration && modifiers.Any(SyntaxKind.StaticKeyword))
|| (type == SyntaxKind.MethodDeclaration && ((MethodDeclarationSyntax)member).ExplicitInterfaceSpecifier != null)
|| (type == SyntaxKind.PropertyDeclaration && ((PropertyDeclarationSyntax)member).ExplicitInterfaceSpecifier != null)
|| (type == SyntaxKind.IndexerDeclaration && ((IndexerDeclarationSyntax)member).ExplicitInterfaceSpecifier != null))
|| (type == SyntaxKind.IndexerDeclaration && ((IndexerDeclarationSyntax)member).ExplicitInterfaceSpecifier != null)
|| (type == SyntaxKind.EventDeclaration && ((EventDeclarationSyntax)member).ExplicitInterfaceSpecifier != null))
Comment thread
AArnott marked this conversation as resolved.
Resolved
{
accessibility = AccessLevel.Public;
}
Expand Down
54 changes: 54 additions & 0 deletions test/StyleCop.Analyzers.Test/OrderingRules/SA1201UnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -708,5 +708,59 @@ public event System.Action TestEvent4 { add { } remove { } }
";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}

/// <summary>
/// Verifies that explicit interface events use public accessibility when accessibility precedes kind.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(1823, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1823")]
public async Task TestExplicitInterfaceEventWithAccessibilityFirstOrderingAsync()
{
var testCode = @"public interface IExample
{
event System.Action Changed;
}

public class Example : IExample
{
public void PublicMethod() { }
event System.Action IExample.{|#0:Changed|} { add { } remove { } }
}
";

var fixedCode = @"public interface IExample
{
event System.Action Changed;
}

public class Example : IExample
{
event System.Action IExample.Changed { add { } remove { } }
public void PublicMethod() { }
}
";

var settings = @"{
""settings"": {
""orderingRules"": {
""elementOrder"": [
""accessibility"",
""kind"",
""constant"",
""static"",
""readonly""
]
}
}
}";

await VerifyCSharpFixAsync(
testCode,
settings,
new[] { Diagnostic().WithLocation(0).WithArguments("An event", "a method") },
fixedCode,
CancellationToken.None).ConfigureAwait(false);
}
}
}
92 changes: 88 additions & 4 deletions test/StyleCop.Analyzers.Test/OrderingRules/SA1202UnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -866,7 +866,7 @@ class Test : IA
{
private event EventHandler TestEvent2;

event EventHandler IA.TestEvent1 { add { } remove { } }
event EventHandler IA.{|#0:TestEvent1|} { add { } remove { } }

public int Q { get; set; }

Expand Down Expand Up @@ -898,7 +898,7 @@ void IA.TestMethod1() { }

DiagnosticResult[] expected =
{
// explicit interface events are considered private by StyleCop
Diagnostic().WithLocation(0).WithArguments("public", "private"),
Diagnostic().WithLocation(34, 12).WithArguments("public", "protected"),
Diagnostic().WithLocation(41, 15).WithArguments("public", "protected"),
Diagnostic().WithLocation(45, 13).WithArguments("public", "protected"),
Expand All @@ -920,10 +920,10 @@ internal interface IA

class Test : IA
{
private event EventHandler TestEvent2;

event EventHandler IA.TestEvent1 { add { } remove { } }

private event EventHandler TestEvent2;

public int Q { get; set; }

string IA.T
Expand Down Expand Up @@ -1362,5 +1362,89 @@ public async Task TestStaticAndInstanceFieldsDoNotExcuseOrderAsync()
var expected = Diagnostic().WithLocation(0).WithArguments("public", "private");
await VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
}

/// <summary>
/// Verifies that explicit interface events are ordered as public members.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(1823, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1823")]
public async Task TestExplicitInterfaceEventAndPublicEventHaveSameAccessLevelAsync()
{
var testCode = @"public interface IExample
{
event System.Action Changed;
}

public class Example : IExample
{
event System.Action IExample.Changed { add { } remove { } }
public event System.Action PublicChanged { add { } remove { } }
}
";

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

/// <summary>
/// Verifies that an explicit interface event is moved before a private event by the code fix.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(1823, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1823")]
public async Task TestExplicitInterfaceEventCodeFixAsync()
{
var testCode = @"public interface IExample
{
event System.Action Changed;
}

public class Example : IExample
{
private event System.Action PrivateChanged { add { } remove { } }
event System.Action IExample.{|#0:Changed|} { add { } remove { } }
}
";

var fixedCode = @"public interface IExample
{
event System.Action Changed;
}

public class Example : IExample
{
event System.Action IExample.Changed { add { } remove { } }
private event System.Action PrivateChanged { add { } remove { } }
}
";
var expected = Diagnostic().WithLocation(0).WithArguments("public", "private");
await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
}

/// <summary>
/// Verifies that a non-explicit event without an access modifier remains private for ordering.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(1823, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1823")]
public async Task TestNonExplicitEventRemainsPrivateAsync()
{
var testCode = @"public class Example
{
event System.Action ImplicitChanged { add { } remove { } }
public event System.Action {|#0:PublicChanged|} { add { } remove { } }
}
";

var fixedCode = @"public class Example
{
public event System.Action PublicChanged { add { } remove { } }
event System.Action ImplicitChanged { add { } remove { } }
}
";

var expected = Diagnostic().WithLocation(0).WithArguments("public", "private");
await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
}
}
}
25 changes: 25 additions & 0 deletions test/StyleCop.Analyzers.Test/OrderingRules/SA1204UnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,31 @@ private static void ExampleMethod()
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}

/// <summary>
/// Verifies that an explicit interface event followed by a private static event is correctly ordered.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(1823, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1823")]
public async Task TestExplicitInterfaceEventFollowedByPrivateStaticEventAsync()
{
var testCode = @"
public interface TestInterface
{
event System.Action Changed;
}

public class TestClass : TestInterface
{
event System.Action TestInterface.Changed { add { } remove { } }

private static event System.Action StaticChanged { add { } remove { } }
}
";

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

/// <summary>
/// Verifies that the analyzer will properly incomplete members.
/// </summary>
Expand Down
Loading