C# Interview Question #9

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

C# & .NET Fundamentals Junior Beginner

Quick Interview Answer

A const field represents a compile-time constant. Its value must be known at compile time and cannot be changed.

Detailed Explanation

A const field represents a compile-time constant. Its value must be known at compile time and cannot be changed.

A readonly field can receive its value at declaration time or in a constructor. This makes readonly suitable for values determined at runtime but that should not be reassigned afterward.

readonly fields are especially common in ASP.NET Core dependency injection, where injected services are stored in private readonly fields.

Code Example

public const double Pi = 3.14159;

private readonly ApplicationDbContext _context;

public ProductsController(ApplicationDbContext context)
{
    _context = context;
}