Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print Single and Multiple variable in C#
In C#, displaying variable values to the console is fundamental for debugging and output purposes. You can print single or multiple variables using various methods with Console.WriteLine().
Syntax
Following is the syntax for printing a single variable −
Console.WriteLine(variable);
Console.WriteLine("Text: " + variable);
Following is the syntax for printing multiple variables −
Console.WriteLine("Values: {0} {1}", var1, var2);
Console.WriteLine($"Values: {var1} {var2}");
Printing a Single Variable
You can print a single variable by passing it directly to Console.WriteLine() or by concatenating it with text using the + operator −
using System;
class Program {
static void Main() {
int a = 10;
string name = "Alice";
Console.WriteLine(a);
Console.WriteLine("Value: " + a);
Console.WriteLine("Name: " + name);
}
}
The output of the above code is −
10 Value: 10 Name: Alice
Printing Multiple Variables
Using String Formatting with Placeholders
The most common approach uses placeholders {0}, {1}, etc., where the numbers correspond to the parameter positions −
using System;
class Program {
static void Main() {
int a = 10;
int b = 15;
string city = "New York";
double price = 29.99;
Console.WriteLine("Values: {0} {1}", a, b);
Console.WriteLine("Location: {0}, Price: ${1}", city, price);
Console.WriteLine("Sum of {0} and {1} is {2}", a, b, a + b);
}
}
The output of the above code is −
Values: 10 15 Location: New York, Price: $29.99 Sum of 10 and 15 is 25
Using String Interpolation
String interpolation uses the $ prefix and allows you to embed variables directly inside curly braces −
using System;
class Program {
static void Main() {
int age = 25;
string name = "John";
bool isStudent = true;
Console.WriteLine($"Name: {name}, Age: {age}");
Console.WriteLine($"Is student: {isStudent}");
Console.WriteLine($"Next year {name} will be {age + 1} years old");
}
}
The output of the above code is −
Name: John, Age: 25 Is student: True Next year John will be 25 years old
Comparison of Methods
| Method | Syntax | Advantages |
|---|---|---|
| String Concatenation | "Text: " + variable | Simple for few variables |
| Composite Formatting | "Values: {0} {1}", var1, var2 | Better performance, reusable placeholders |
| String Interpolation | $"Values: {var1} {var2}" | Most readable, supports expressions |
Conclusion
C# provides multiple ways to print variables using Console.WriteLine(). String interpolation with $ is the most modern and readable approach, while composite formatting with placeholders offers better performance for complex scenarios.
