All the information is in the existing answers, but I personally wished for a concise summary, so here's an attempt at it; the commands use int
variables for brevity, but they apply analogously to any type, including string
.
To declare multiple variables and:
int i = 0, j = 1; // declare and initialize each; `var` is NOT supported as of C# 8.0
int i, j; // *declare* first (`var` is NOT supported)
i = j = 42; // then *initialize*
// Single-statement alternative that is perhaps visually less obvious:
// Initialize the first variable with the desired value, then use
// the first variable to initialize the remaining ones.
int i = 42, j = i, k = i;
What doesn't work:
You cannot use var
in the above statements, because var
only works with (a) a declaration that has an initialization value (from which the type can be inferred), and (b), as of C# 8.0, if that declaration is the only one in the statement (otherwise you'll get compilation error error CS0819: Implicitly-typed variables cannot have multiple declarators
).
Placing an initialization value only after the last variable in a multiple-declarations statement initializes the last variable only:
int i, j = 1;
// initializes *only* j