Declaring and Using Variables
In C#, a variable must be declared with a specific data type before it can be used. Once declared, it can store values of that type. The syntax for declaring a variable is: dataType variableName = value;.
Key Concepts
- Variables in C# must be declared with a type.
- The syntax follows
dataType variableName = value;. - Common data types include
int,string, anddouble.
Example of Declaring Variables
Code Example
// Declare variables of different data types
int age = 25;
string name = "John";
double salary = 5000.50;
// Output the values to the console
Console.WriteLine($"Name: {name}, Age: {age}, Salary: {salary}");
Output:
Name: John, Age: 25, Salary: 5000.50
Code Explanation: The variables age, name, and salary are declared with types int, string, and double, respectively. The Console.WriteLine() method is used to display their values using string interpolation.
Output Explanation: The values assigned to the variables are printed to the console: John, 25, and 5000.50.