S3218 — Inner class members should not shadow outer class "static" or type members

Language
C#
Type
Code smell
Severity
Critical
Tags
design, pitfall

Why is this an issue?

Naming the members of an inner class the same as the static members of its enclosing class is possible but generally considered a bad practice. That’s because maintainers may be confused about which members are being used in a given context. Instead the inner class member should be given distinct and descriptive name, and all references to it should be updated accordingly.


class Outer
{
  public static int A;

  public class Inner
  {
    public int A; // Noncompliant

    public int MyProp
    {
      get => A; // Returns inner A. Was that intended?
    }
  }
}

Here’s an example of compliant code after renaming the inner class member, this way the property will return the Outer A:


class Outer
{
  public static int A;

  public class Inner
  {
    public int B; // Compliant

    public int MyProp
    {
      get => A; // Returns outer A
    }
  }
}

Or if you want to reference the Inner A field:


class Outer
{
  public static int B;

  public class Inner
  {
    public int A; // Compliant

    public int MyProp
    {
      get => A; // Returns inner A
    }
  }
}

Resources

Documentation

↑ Back to top