C# Variables - Real-Life Examples
Real-Life Examples
In our examples, we often use short variable names, like x or myNum. This keeps the examples simple.
In real programs, variables store real-world data, and their names tell what the data is.
The following program stores information about a student:
Example
// Student data
string studentName = "Liam";
int studentId = 15;
int studentAge = 23;
double studentFee = 75.25;
char studentGrade = 'B';
// Print variables
Console.WriteLine("Student name: " + studentName);
Console.WriteLine("Student ID: " + studentId);
Console.WriteLine("Student age: " + studentAge);
Console.WriteLine("Student fee: " + studentFee);
Console.WriteLine("Student grade: " + studentGrade);
Each variable stores a different type of data, but they are all used together in one program.
Calculate the Area of a Rectangle
Variables are often used to store values, do a calculation, and then show the result.
In this example, we calculate the area of a rectangle, by multiplying its length and width. The * symbol means multiply:
Example
// Create integer variables
int length = 4;
int width = 6;
// Calculate the area of the rectangle
int area = length * width;
// Print the variables
Console.WriteLine("Length is: " + length);
Console.WriteLine("Width is: " + width);
Console.WriteLine("Area of the rectangle is: " + area);
Count Points in a Game
The value of a variable can change while the program runs.
In this example, a player starts with 0 points, and then scores 10 points:
Example
string playerName = "Jenny";
int points = 0;
Console.WriteLine(playerName + " has " + points + " points");
// Jenny scores 10 points
points = points + 10;
Console.WriteLine(playerName + " has " + points + " points");
The line points = points + 10; takes the old value of points, adds 10 to it, and stores the result back in points. So points changes from 0 to 10.