Home
Search
C# Multiple Local VariablesAssign multiple local variables on one line. Understand local syntax.
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.
Example syntax:
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.
Main 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.
C# program that initializes multiple variables
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.
Performance 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.
Home
© 2007-2021 sam allen. see site info on the changelog