Multiple Local Variables
This page was last reviewed on Jun 10, 2021.
Dot Net Perls
Multiple locals. 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.
C# syntax notes. The C# language allows complex declarator statements. And for multiple variables, we only need to specify the type name once.
Syntax intro. 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;
Example code. We introduce a program that uses the multiple local variable declarator syntax. You can declare and optionally assign several variables in a single statement.
Note The type of all of the variables declared or assigned this way is the same in a single statement.
Detail The first section declares and assigns 3 int locals. The second section declares and assigns 3 constant string literal references.
String Literal
Also The final section declares three local ints but only assigns one of them.
int, uint
Warning Some programming guidelines discourage this syntax as it is somewhat unusual. In these situations, it should be avoided.
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
A discussion. Whenever a method is called, it is pushed onto the stack frame. At this point 3 different spaces of memory are allocated.
So All the local variables used throughout the method are allocated in one memory space.
And The evaluation stack and parameter slots are separately allocated. They are not part of the local variable memory.
Detail It follows that the count of variables can impact the performance hit when calling a C# method.
A summary. We looked at the multiple local variable declaration and assignment syntax. This syntax allows you to condense the syntax of variable declarations.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 10, 2021 (image).
© 2007-2024 Sam Allen.