Static Keyword in C#

Static Keyword in C

The static keyword in C# has different meanings depending on its usage. It applies to methods, properties, fields, and classes. We'll explore each of these in detail.

Static Methods and Properties

  • Non-static Methods: Can only be called on an instance of the class they belong to.
    • Example: An Employee class with a Pay method to generate a pay invoice for an individual employee.
    • The Pay method may use private fields within the Employee class (e.g., bank and account details).
    • You can't call employee.Pay without an instance because there's no specific employee with a name, salary, and bank account number.
  • Static Methods: Called on the class itself, not an instance.
    • Don't have special access to an individual instance.
    • Used for more general functionality.
    • Example: A PayAllEmployees method that takes a list of employees and pays them all.
      • No reference to a specific employee is needed.
      • Can be invoked as Employee.PayAllEmployees(employees);.
  • Recommendation: Use static methods if the method doesn't need to access instance fields or non-static methods of an individual instance.

Static Fields

  • Definition: Fields that can be accessed without requiring an instance of the class.
    • Accessed from the class itself.
    • Example: A TaxRate that is shared by all employees.
      • private static decimal TaxRate = 0.1m; (m is the suffix for the decimal type)
  • Behavior:
    • A static field has the same value for all instances of the class.
    • It can be modified, affecting all instances.
      • Example: Increasing the TaxRate each time an employee gets paid.
      • The change persists for the life of the program.
  • Caution:
    • Static fields can be problematic because changes in one area can affect everything else.
    • Generally, antithetical to good programming practices.
    • Private static fields can have legitimate uses (e.g., the Singleton design pattern or for memorization optimizations).
  • Public Static Fields:
    • Combine the worst parts of static fields and public fields.
    • Essentially a global variable (which is heavily discouraged in programming).
    • Any code that can see the class can modify the field.
    • Makes the code extremely difficult to debug because the variable could be changed anywhere.

Constants (const)

  • const fields are implicitly static.
  • Safe even if they are public.
  • Example: public const decimal TaxRate = 0.1m;
  • Cannot be modified after initialization.
  • Recommended for magic numbers; give the number a name and declare it as a constant.
  • If a public const is used, keep in mind the impact of later changes on other code. Private const fields do not have this concern.

Static Classes

  • Definition: Classes that cannot be instantiated (no objects can be created from them).
  • Restrictions:
    • Can only contain static methods.
    • Can only contain static fields.
  • Purpose:
    • Imposes an additional restriction on a regular class.
    • Communicates to users that there is no reason to instantiate the class.
    • Prevents inadvertent instantiation.
  • Usage:
    • Typically used for utility classes that group together related and useful methods.
    • Example: System.Math in the .NET standard library.
      • Contains static methods like Math.Max(), Math.Min(), Math.Pow() etc.
      • Cannot be instantiated: new Math() is not allowed.
  • Design Considerations:
    • Potentially have poor cohesion if unrelated methods are grouped together just for convenience.
    • Avoid creating a "Utility" class with a bunch of unrelated static methods.

Summary

  • Use static methods or properties when access to an instance is not required.
  • Avoid static fields unless there is a legitimate need for a private static field.
  • Never use public static fields.
  • Use static classes when appropriate, but avoid collecting unrelated methods for convenience to prevent poor cohesion.