Variables in C#: Declaring and Using Them

In C#, variables are essential for storing and manipulating data. This guide will walk you through the basics of declaring and using variables in C#.

Declaring Variables

To declare a variable in C#, you need to specify its data type and name. Here are some common data types:

  • int: Integer (whole number).
  • double: Double-precision floating-point number (decimal).
  • string: Text (sequence of characters).
  • bool: Boolean (true or false).

Here's how you declare variables:

int age;        // Declaring an integer variable
double price; // Declaring a double variable
string name; // Declaring a string variable
bool isTrue; // Declaring a boolean variable

Initializing Variables

Variables can be initialized when declared. Initializing means giving them an initial value:

int age = 25;                   // Initializing an integer variable
double price = 19.99; // Initializing a double variable
string name = "John Smith"; // Initializing a string variable
bool isTrue = true; // Initializing a boolean variable

Using Variables

Once you've declared and initialized variables, you can use them in your code. Here are some examples:

int myAge = 30;
string greeting = "Hello, ";
string name = "Alice";
bool isStudent = true;
double total = 0.0;
total = price * 2; // Multiplying variables
string fullName = name + " Smith"; // Concatenating strings
bool canVote = (myAge >= 18); // Using variables in expressions


Understanding variables is fundamental to programming in C#. You've learned how to declare, initialize, and use variables with different data types. Variables are the building blocks of your programs, allowing you to store and manipulate data effectively.

Now, practice using variables in your C# code and explore more about data types and variable scope as you continue your journey in C# programming.