C# Multiple Variables - Complete Guide
Working with Multiple Variables
In C#, you can declare and use multiple variables efficiently with different techniques. This includes declaring several variables of the same type in one statement, working with tuples, and using deconstruction or object initializers.
Managing multiple variables in a clean way helps keep your code concise, consistent, and easier to read.
Declaring Multiple Variables
You can declare multiple variables of the same type in a single statement, or initialize some immediately while assigning values to others later.
Example
using System;
namespace MultipleVariables
{
class Program
{
static void Main(string[] args)
{
int x = 5, y = 10, z = 15;
string firstName = "John", lastName = "Doe", title = "Mr.";
double price = 19.99, discount = 0.1, finalPrice;
finalPrice = price - (price * discount);
Console.WriteLine("x: " + x + ", y: " + y + ", z: " + z);
Console.WriteLine($"Name: {title} {firstName} {lastName}");
Console.WriteLine($"Price: {price:C}, Discount: {discount:P0}, Final: {finalPrice:C}");
int a, b = 20, c;
a = 10;
c = 30;
Console.WriteLine($"a: {a}, b: {b}, c: {c}");
// Tuple deconstruction as shorthand for multiple variables
var (width, height, depth) = (100, 200, 50);
Console.WriteLine($"Dimensions: {width}x{height}x{depth}");
}
}
}
Output
x: 5, y: 10, z: 15 Name: Mr. John Doe Price: $19.99, Discount: 10%, Final: $17.99 a: 10, b: 20, c: 30 Dimensions: 100x200x50
Tuples for Multiple Values
Tuples provide a way to group multiple values without creating a separate class. They can be named or unnamed, and support deconstruction. They are especially useful for returning multiple values from a method or quickly swapping variables.
Example
using System;
namespace TupleExamples
{
class Program
{
static void Main(string[] args)
{
(string, int, double) person1 = ("Alice", 25, 55000.50);
var person2 = (Name: "Bob", Age: 30, Salary: 60000.75);
Console.WriteLine($"Person1: {person1.Item1}, {person1.Item2}, {person1.Item3:C}");
Console.WriteLine($"Person2: {person2.Name}, {person2.Age}, {person2.Salary:C}");
var (name, age, salary) = person2;
Console.WriteLine($"Deconstructed: {name}, {age}, {salary:C}");
var stats = CalculateStatistics(10, 20, 30, 40, 50);
Console.WriteLine($"Average: {stats.average}, Sum: {stats.sum}, Count: {stats.count}");
int first = 10, second = 20;
Console.WriteLine($"Before swap: first={first}, second={second}");
(first, second) = (second, first);
Console.WriteLine($"After swap: first={first}, second={second}");
}
static (double average, int sum, int count) CalculateStatistics(params int[] numbers)
{
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
double average = (double)sum / numbers.Length;
return (average, sum, numbers.Length);
}
}
}
Output
Person1: Alice, 25, $55,000.50 Person2: Bob, 30, $60,000.75 Deconstructed: Bob, 30, $60,000.75 Average: 30, Sum: 150, Count: 5 Before swap: first=10, second=20 After swap: first=20, second=10