Skip to content

Commit ed27215

Browse files
authored
Add code example for CA1822 rule (#48964) (#48965)
1 parent eeaf182 commit ed27215

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

docs/fundamentals/code-analysis/quality-rules/ca1822.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ helpviewer_keywords:
1010
- CA1822
1111
author: gewarren
1212
ms.author: gewarren
13+
dev_langs:
14+
- CSharp
1315
---
1416
# CA1822: Mark members as static
1517

@@ -33,6 +35,10 @@ Members that do not access instance data or call instance methods can be marked
3335

3436
Mark the member as static (or Shared in Visual Basic) or use 'this'/'Me' in the method body, if appropriate.
3537

38+
## Example
39+
40+
:::code language="csharp" source="snippets/csharp/all-rules/ca1822.cs" id="snippet1":::
41+
3642
## When to suppress warnings
3743

3844
It is safe to suppress a warning from this rule for previously shipped code for which the fix would be a breaking change.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
using System;
2+
using System.Collections.Generic;
3+
4+
namespace ca1822
5+
{
6+
//<snippet1>
7+
public class Printer
8+
{
9+
private readonly List<char> _items = [
10+
'H', 'e', 'l', 'l', 'o',
11+
];
12+
13+
public void PrintHello()
14+
{
15+
BadPrintHelloInternal();
16+
GoodPrintHelloInternal();
17+
GoodPrintHelloStaticInternal();
18+
}
19+
20+
// This method violates the rule.
21+
private void BadPrintHelloInternal()
22+
{
23+
Console.WriteLine("Hello");
24+
}
25+
26+
// This methods satisfies the rule.
27+
private void GoodPrintHelloInternal()
28+
{
29+
Console.WriteLine(string.Join(string.Empty, this._items));
30+
}
31+
32+
private static void GoodPrintHelloStaticInternal()
33+
{
34+
Console.WriteLine("Hello");
35+
}
36+
}
37+
//</snippet1>
38+
}

0 commit comments

Comments
 (0)