C# Variables: Assign, Read and Update Values
Duration: 10 Minutes
Level: Beginner
Audience: Students, Developers, Educators
Track: .NET Development
Introduction
Variables are temporary storage containers designed to hold data that can change during program execution. In this exercise, you will practice both writing to (setting) and reading from (getting) variables, which is fundamental for all C# applications.
Exercise – Working with Variables
1. Create Your First Variable
Clear any previous code and declare a variable:
string firstName;
firstName = "Bob";
-
Declaration: Specify the data type (
string) and variable name (firstName) -
Assignment: Use the
=operator to assign a value ("Bob")
Assigning a value is also called setting a variable.
2. Common Assignment Errors
Right-to-left assignment: The compiler reads the value on the right and stores it in the variable on the left. Reversing this causes an error:
"Bob" = firstName; // ❌ Error CS0131
Type mismatch: Variables can only hold values of their declared type:
int firstName;
firstName = "Bob"; // ❌ Error CS0029
Remember: a variable must match its data type.
3. Retrieve a Variable’s Value
Use the variable name to get the stored value:
string firstName;
firstName = "Bob";
Console.WriteLine(firstName);
Output:
Bob
Retrieving a value is also called getting a variable.
4. Reassign Variable Values
Variables can be reused and updated multiple times:
string firstName;
firstName = "Bob";
Console.WriteLine(firstName);
firstName = "Liem";
Console.WriteLine(firstName);
firstName = "Isabella";
Console.WriteLine(firstName);
firstName = "Yasmin";
Console.WriteLine(firstName);
Output:
Bob
Liem
Isabella
Yasmin
5. Initialize a Variable
Assign a value at the time of declaration:
string firstName = "Bob";
Console.WriteLine(firstName);
-
Output:
Bob -
Initialization avoids unassigned variable errors like
CS0165.
Recap
-
You must set a value before you can get a value
-
Variables can be initialized at the point of declaration
-
Assignment is right-to-left using
= -
Retrieving a value is done by using the variable name
Understanding how to set, get, and initialize variables is a core skill in C#.
Continue learning
- Module 2 lesson guide
- Declare C# Variables: Types and Naming Rules
- C# var Keyword: Implicitly Typed Local Variables
Further reading: Microsoft documentation.
Assignment troubleshooting
Does assigning one variable to another keep them linked?
For the simple numeric values in this lesson, the assignment copies the value. If int copy = original is followed by changing original, copy retains its earlier integer value. More complex reference types have additional behavior outside this exercise.
Practice and check
Start original at 5, assign it to copy, then set original to 9. Print both values: original should be 9 and copy should be 5. Explain the statement order before running the program.
Comments
Post a Comment