S1118 — Utility classes should not have public constructors

Language
C#
Type
Code smell
Severity
Major
Tags
design

Why is this an issue?

Whenever there are portions of code that are duplicated and do not depend on the state of their container class, they can be centralized inside a "utility class". A utility class is a class that only has static members, hence it should not be instantiated.

How to fix it

To prevent the class from being instantiated, you should define a non-public constructor. This will prevent the compiler from implicitly generating a public parameterless constructor.

Alternatively, adding the static keyword as class modifier will also prevent it from being instantiated.

Code examples

Noncompliant code example


public class StringUtils // Noncompliant: implicit public constructor
{
  public static string Concatenate(string s1, string s2)
  {
    return s1 + s2;
  }
}

or


public class StringUtils // Noncompliant: explicit public constructor
{
  public StringUtils()
  {
  }

  public static string Concatenate(string s1, string s2)
  {
    return s1 + s2;
  }
}

Compliant solution


public static class StringUtils // Compliant: the class is static
{
  public static string Concatenate(string s1, string s2)
  {
    return s1 + s2;
  }
}

or


public class StringUtils // Compliant: the constructor is not public
{
  private StringUtils()
  {
  }

  public static string Concatenate(string s1, string s2)
  {
    return s1 + s2;
  }
}

↑ Back to top