What is the difference between `const` and `readonly` in C#?

Beginner

Answer

const:

  • Compile-time constant
  • Must be initialized at declaration
  • Value cannot change
  • Implicitly static
  • Only primitive types, null, or string literals
    readonly:
  • Runtime constant
  • Can be initialized at declaration or in constructor
  • Value can be set once per instance
  • Can be instance or static
  • Can hold any type including complex objects
public class Example
{
    const int MAX_SIZE = 100;           // Compile-time constant
    readonly DateTime createdDate;      // Runtime constant
    public Example()
    {
        createdDate = DateTime.Now;     // Can set in constructor
    }
}