How to Resolve Error "CS0819: Implicitly-typed variables cannot have multiple declarators" in C#
The Compiler Error CS0819 is a syntax restriction error regarding the var keyword. The message reads: "Implicitly-typed variables cannot have multiple declarators".
In C#, you are allowed to declare multiple variables of the same explicit type in a single statement using commas (e.g., int a = 1, b = 2;). However, the var keyword (Implicit Typing) does not support this syntax. When you use var, the compiler infers the type from the expression on the right. To keep type inference logic deterministic and readable, C# enforces a rule: One var declaration per statement.
This guide explains the restriction and provides standard workarounds.
Understanding Multiple Declarators
A "Declarator" is the part of the statement that names the variable and assigns it a value.
- Explicit Type:
int x = 10, y = 20;- Here,
intapplies to bothxandy. This is valid.
- Here,
- Implicit Type:
var x = 10, y = 20;- Here, the compiler rejects the syntax. Even though both are integers,
varcannot be distributed across multiple variables in one line.
- Here, the compiler rejects the syntax. Even though both are integers,
Scenario 1: Comma-Separated Declarations
This is the most direct cause. You try to shorten your code by declaring two variables on one line using var.
Example of error
public void Setup()
{
// ⛔️ Error CS0819: Implicitly-typed variables cannot have multiple declarators.
var a = 10, b = 20;
// Also invalid even if types differ (which would be invalid explicitly anyway)
// var s = "Hello", i = 50;
}
Solution 1: Use Separate Statements
The cleanest fix is to declare each variable on its own line using var.
public void Setup()
{
// ✅ Correct: Each 'var' infers its own type independently.
var a = 10;
var b = 20;
}
Solution 2: Use Explicit Typing
If you really want them on the same line, and they are the same type, simply replace var with the concrete type.
public void Setup()
{
// ✅ Correct: Standard C# syntax for multiple declarators.
int a = 10, b = 20;
}
Scenario 2: The for Loop Limitation
This error frequently catches developers when writing for loops. It is common to initialize two index variables (e.g., one moving forward, one moving backward) in the loop header.
Example of error
Attempting to use var for multiple loop variables.
public void ReverseArray(int[] arr)
{
// ⛔️ Error CS0819: You cannot use 'var' for both i and j here.
for (var i = 0, j = arr.Length - 1; i < j; i++, j--)
{
// Swap logic...
}
}
Solution 1: Use Explicit Types
Since loop counters are almost always integers, explicit typing is the best fix here.
public void ReverseArray(int[] arr)
{
// ✅ Correct: Using 'int' allows multiple declarators.
for (int i = 0, j = arr.Length - 1; i < j; i++, j--)
{
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}