Skip to main content

How to Resolve Error "CS0822: Implicitly-typed variables cannot be constant" in C#

The Compiler Error CS0822 is a syntax restriction error. The message reads: "Implicitly-typed variables cannot be constant".

In C#, the var keyword implies that the compiler determines the type of the variable based on the value assigned to it. The const keyword indicates that a value is immutable and known at compile-time. The C# language specification explicitly forbids combining these two keywords. When defining a constant, you are required to be explicit about its data type to ensure the contract of that constant is clear and unchangeable.

This guide explains why var and const are mutually exclusive and how to declare constants correctly.

Understanding the Conflict

  • var: Used for local variables where the type is inferred.
  • const: Used for values that never change.

While it seems logical that the compiler could infer const var x = 10 is a const int, C# requires constants to have explicitly declared types. This prevents accidental type changes (e.g., changing 10 to 10.5 would silently change the type from int to double if inference were allowed, potentially breaking code that relies on the constant's specific type).

Scenario: Attempting to Declare a const var

This error commonly occurs when a developer wants the convenience of type inference but also wants to ensure the value remains immutable locally.

Example of error

public void CalculateCircle()
{
// ⛔️ Error CS0822: Implicitly-typed variables cannot be constant.
// You cannot mix 'const' and 'var'.
const var Pi = 3.14159;

// ⛔️ Error CS0822: Also applies to other types
const var Message = "Hello World";
}

Solution 1: Use Explicit Type (Keep const)

If the immutability of the value is your priority (i.e., it must be a constant), you must replace var with the specific data type (int, double, string, etc.).

public void CalculateCircle()
{
// ✅ Correct: Explicitly defined as double
const double Pi = 3.14159;

// ✅ Correct: Explicitly defined as string
const string Message = "Hello World";
}

Solution 2: Remove const (Keep var)

If using type inference (var) is your priority and you don't strictly need the compile-time constant behavior, simply remove the const keyword. The variable will be standard (mutable), but the type will be inferred automatically.

public void CalculateCircle()
{
// ✅ Correct: Type is inferred as double, but variable is mutable.
var Pi = 3.14159;

// Note: You can now accidentally change Pi later:
// Pi = 0; // This would be allowed.
}

Conclusion

CS0822 enforces explicit typing for constants.

  1. Prioritize Intent: Do you need a constant? Or do you just want type inference?
  2. If Constant: Use const double x = ... (Explicit type).
  3. If Inference: Use var x = ... (Remove const).