Before understanding what a variable is, it’s crucial to know why we need variables.
Why Do We Need Variables?
There are common and interesting reasons behind using variables. Suppose you have a task to add 10 and 20 and display the result. In any programming language, you might do something like this:
I used C#
Console.WriteLine("Sum of 10 + 20 is " + (10 + 20));
The above code uses Console.WriteLine is a command that displays text and values on the command line.
Similarly, if you need to subtract 10 from 20, multiply 10 by 20, or divide 20 by 10, you can use similar commands. But what happens if you need to add 10 and 20 and then divide the total by 5? Things become more complex, especially if you need to get these values from the user at runtime.
Scenario 1. Static Values
To add 10 and 20 and then divide by 5, you can write:
(10 + 20) / 5
This will give you the answer.
Scenario 2. Using Variables
Using variables, you can achieve the same result with more flexibility:
int a = 10;
int b = 20;
int c = a + b;
int d = c / 5;
This code will also give you the correct answer. Here, a, b, and c store the values 10, 20, and their sum (10 + 20), respectively. d holds the result of dividing c by 5.
The benefit of using variables is that you can store values separately in a, b, c, and d, which allows you to perform calculations dynamically or change the values at runtime. For example, if you want to subtract a from c, you can get the difference between a and b.
Definition of a Variable
“A variable is a container that holds or stores any type of value at compile-time or runtime, allowing you to perform mathematical operations or other tasks dynamically.”
Note. You can also change or assign a new value.
Rules for Naming Variables
|| Syntax: type variableName = value; ||
- A variable name can contain letters (A-Z, a-z), numbers (0-9), and the underscore (_) character.
- A variable name cannot start with a digit.
- A variable name cannot be any C# keyword like int, char, float, double, bool, etc.
- A variable name cannot contain special characters like #, $, %, space, !, etc.
- A variable name should start with an alphabet or an underscore.
I hope this helps you understand variables better. If you liked this blog, don't forget to like and follow me. Feel free to comment anytime if you have any doubts about variables!