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
Employeeclass with aPaymethod to generate a pay invoice for an individual employee. - The
Paymethod may use private fields within theEmployeeclass (e.g., bank and account details). - You can't call
employee.Paywithout an instance because there's no specific employee with a name, salary, and bank account number.
- Example: An
- 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
PayAllEmployeesmethod 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
TaxRatethat 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
TaxRateeach time an employee gets paid. - The change persists for the life of the program.
- Example: Increasing the
- 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)
constfields are implicitlystatic.- 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
constfields 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.Mathin the .NET standard library.- Contains static methods like
Math.Max(),Math.Min(),Math.Pow()etc. - Cannot be instantiated:
new Math()is not allowed.
- Contains static methods like
- 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.