Understanding Variables in C# with Examples
Imagine you have a box where you store different things—like books, clothes, or toys. Each box has a label so you know what’s inside.
In C#, variables work the same way! They are like labeled containers that store values, such as numbers, text, or true/false values.
For example, if you want to store a person’s age in a program, you can create a variable like this:
int age = 25;
Here, int
means it’s a number (integer), age
is the variable name, and 25
is the stored value.
Sounds simple? Let’s dig deeper!
What is a Variable?
A variable is a placeholder in memory where you store data. The data inside a variable can change as the program runs, just like you can replace things inside a box.
Real-Life Example
Let’s say you are running a coffee shop. You need to track how many cups of coffee you sell each day. Instead of writing the number on paper, you can use a variable in C#:
int coffeeSold = 50;
Console.WriteLine("Cups of coffee sold today: " + coffeeSold);
If more cups are sold, you update the variable:
coffeeSold = coffeeSold + 10;
Console.WriteLine("Updated coffee sales: " + coffeeSold);
Now, the variable holds 60 instead of 50!
Declaring and Using Variables in C#
To create a variable, you follow this pattern:
dataType variableName = value;
Here’s a breakdown:
dataType
→ What kind of value will be stored (e.g., number, text, true/false).variableName
→ A name for the variable (must be unique).value
→ The actual data stored in the variable.
Let’s see some examples:
1. Storing Numbers
int apples = 10;
double price = 5.99;
int
is for whole numbers (e.g., 10, 20, -5).double
is for decimal numbers (e.g., 5.99, 3.14).
2. Storing Text
string name = "Steven";
Console.WriteLine("Hello, " + name);
string
holds text (words, sentences, names).- The
+
operator joins text together.
3. Storing True/False Values
bool isRaining = false;
bool isWeekend = true;
bool
(Boolean) holds true or false values.
Changing Variable Values
Variables can change during the program. For example:
int score = 0;
Console.WriteLine("Score: " + score);
score = score + 10; // Updating the variable
Console.WriteLine("New Score: " + score);
Output:
Score: 0
New Score: 10
Getting User Input in a Variable
Let’s make it interactive! You can ask the user for input and store it in a variable:
Console.Write("Enter your name: ");
string userName = Console.ReadLine();
Console.WriteLine("Welcome, " + userName + "!");
Output
Enter your name: Steven
Welcome, Steven!
This is useful when you want the program to work with different users.
Conclusion
Variables are like labeled boxes in C#. They store values, and you can change them anytime. You can use them for numbers, text, or true/false values. Plus, you can even take user input and store it in variables!
As you write more programs, you’ll see how powerful variables are. Keep practicing and experiment with different types. Happy coding!