C# Multiple Local Variable Declarations

In C#, you can declare and initialize multiple local variables of the same type in a single statement using the comma operator. This provides a concise way to declare several variables at once, making your code more readable and reducing repetition.

Syntax

Following is the syntax for declaring multiple local variables of the same type −

dataType variable1 = value1, variable2 = value2, variable3 = value3;

You can also declare variables without initialization −

dataType variable1, variable2, variable3;

Basic Multiple Variable Declaration

The following example demonstrates declaring four integer variables in a single statement −

using System;

class Demo {
    static void Main() {
        int a = 20, b = 70, c = 40, d = 90;
        Console.WriteLine("Values: {0} {1} {2} {3}", a, b, c, d);
    }
}

The output of the above code is −

Values: 20 70 40 90

Mixed Declaration and Assignment

You can mix initialized and uninitialized variables in the same declaration statement −

using System;

class Program {
    static void Main() {
        int x = 10, y, z = 30;
        y = 20; // Assign value later
        
        Console.WriteLine("x = {0}", x);
        Console.WriteLine("y = {0}", y);
        Console.WriteLine("z = {0}", z);
        
        double price = 99.99, tax = 8.25, total;
        total = price + (price * tax / 100);
        Console.WriteLine("Total: ${0:F2}", total);
    }
}

The output of the above code is −

x = 10
y = 20
z = 30
Total: $108.24

Using Multiple Variables in Calculations

Multiple variable declarations are particularly useful when working with related calculations −

using System;

class Calculator {
    static void Main() {
        int num1 = 15, num2 = 25, sum, difference, product;
        
        sum = num1 + num2;
        difference = num2 - num1;
        product = num1 * num2;
        
        Console.WriteLine("Numbers: {0} and {1}", num1, num2);
        Console.WriteLine("Sum: {0}", sum);
        Console.WriteLine("Difference: {0}", difference);
        Console.WriteLine("Product: {0}", product);
    }
}

The output of the above code is −

Numbers: 15 and 25
Sum: 40
Difference: 10
Product: 375

Key Rules

  • All variables in a multiple declaration must be of the same data type.

  • Variables can be initialized or left uninitialized in the same statement.

  • Each variable name must be unique within its scope.

  • Uninitialized variables must be assigned values before use.

Conclusion

Multiple local variable declarations in C# allow you to declare several variables of the same type in a single statement using comma separation. This feature improves code readability and is particularly useful when working with related variables that will be used together in calculations or operations.

Updated on: 2026-03-17T07:04:35+05:30

864 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements