A single C# statement can assign multiple local variables. C-style languages often allow you to use commas to declare multiple variables in one statement.
The C# language allows complex declarator statements. And for multiple variables, we only need to specify the type name once.
Let us consider the C# syntax for multiple locals on a single statement. The comma character is used, and the type name is repeated.
int x = 1, y = 2; SAME AS: int x = 1; int y = 2;
We introduce a program that uses the multiple local variable declarator syntax. You can declare and optionally assign several variables in a single statement.
int
locals. The second section declares and assigns 3 constant string
literal references.using System; class Program { static void Main() { // // Declare and initialize three local variables with same type. // ... The type int is used for all three variables. // int i = 5, y = 10, x = 100; Console.WriteLine("{0} {1} {2}", i, y, x); // // Declare and initialize three constant strings. // const string s = "dot", a = "net", m = "perls"; Console.WriteLine("{0} {1} {2}", s, a, m); // // Declare three variables. // ... We initialize one of them. // int j = 1, k, z; Console.WriteLine(j); k = z = 0; // Initialize the others Console.WriteLine("{0} {1}", k, z); } }5 10 100 dot net perls 1 0 0
Whenever a method is called, it is pushed onto the stack frame. At this point 3 different spaces of memory are allocated.
We looked at the multiple local variable declaration and assignment syntax. This syntax allows you to condense the syntax of variable declarations.