In .NET development, you often need to define data that doesn't change or belongs to the class itself rather than a specific object. C# provides three keywords for these purposes: static, const, and readonly.
At first, all three may look similar because they are often used with variables or fields. However, they are completely different concepts and are used for different purposes.
What is Static in C#?
The static keyword belongs to the class itself rather than the object. Normally, when we create objects, each object gets its own copy of variables. But static members are shared among all objects.
Key Characteristics:
- Shared Memory: There is only one copy of a static variable in memory.
- Not a Constant: Unless combined with
readonly, a static variable can be changed. - Utility: Commonly used for counters, global settings, or helper methods (like
Math.Sqrt()).
Example 1
Here is an example that shows the use of static variables.
public class User
{
public static int TotalUsers = 0; // Shared by everyone
public User()
{
TotalUsers++; // Every time a new user is made, the shared count goes up
}
}Example 2
class Employee
{
public static string CompanyName = "ABC Technologies";
}
class Program
{
static void Main()
{
// Note that we are not creating an objet here.
Console.WriteLine(Employee.CompanyName);
}
}Output:
ABC TechnologiesHere public static string CompanyName belongs to the class itself. We accessed it using Employee.CompanyName without creating an object.
What is Const in C#?
The const keyword is used for values that never change. Once a constant variable is assigned a value, it cannot be modified.
Key Characteristics:
- Compile-Time: The value must be assigned when you declare it. And the value should be a compile-time constant.
- Absolute: It cannot be changed by a constructor or any other method.
- Implicitly Static: You access it using the Class name (e.g.,
Configuration.MaxUsers), not an instance. In other words, we can say that a const is a static variable that cannot be changed. - Performance: The compiler literally replaces the variable name with the value everywhere in your code, making it very fast.
Basic Example:
public class MathConstants
{
public const double Pi = 3.14159; // Must assign here
}
// Usage
Console.WriteLine(MathConstants.Pi);What is Readonly in C#?
A readonly field is a "run-time" constant. This means the value can be calculated or assigned when the application starts, but once assigned, it cannot be changed again.
Key Characteristics:
- Run-Time: You can assign the value in the Constructor. This allows you to set the value based on external data (like a database or user input).
- Instance-Based: By default, each object you create can have a different
readonlyvalue (unless you also make itstatic). - Flexibility: It is safer for versioning than
const.
public class Report
{
public readonly DateTime CreatedAt;
public Report()
{
// Assigned at run-time when the object is created and cannot be changed later.
CreatedAt = DateTime.Now;
}
}Summary Table
| Feature | const | readonly | static |
|---|---|---|---|
| Assignment Time | Compile-time only | Constructor or Declaration | Anytime (unless readonly) |
| Can change? | Never | Only in Constructor | Yes |
| Scope | Class-level (shared) | Instance-level (per object) | Class-level (shared) |
| Memory | Replaced with value | Separate per instance | One copy for the class |
Practice Questions
1. You need to store the version number of your software (e.g., "1.0.4"). Which keyword should you use?
Answer: const. Since the version number is known when you build the app and won't change while it's running, const is the most efficient choice.
2. You want a variable that tracks how many times a specific method has been called across the entire application. Which keyword is required?
Answer: static. You need a variable that belongs to the class itself so that every call to the method increments the same shared memory location.
3. What is the main limitation of a const variable compared to a readonly variable?
Answer: A const variable cannot be assigned a value that is calculated at run-time (like DateTime.Now or a value from a database). It must be a "literal" value like a string or a number.
4. Can you have a static readonly variable? If so, what does it do?
Answer: Yes! A static readonly variable is a shared variable (one per class) that can only be assigned once (usually in a static constructor). It is the best way to handle "global constants" that depend on run-time logic.