What are variables in C#?
There is always something called a variable in any programming language, not just C#. In this tutorial, I will briefly describe such variables.
What is a variable?
A variable is a box for temporarily storing a value.
When you were a student, you may have learned that x = 1, y = 2, z =3.
This is exactly what a variable is.
For example:
x = 3;
x = x + 1;
Isn't it strange that x = x + 1? You may be thinking, "What's wrong with that?
In programming, "= (equal)" means to assign to the left-hand side, and most programming languages, not just C#, are written in the same way.
Since it means to assign to the left-hand side, x = x + 1, the content of variable x is 4.
A variable, in this case, is a number, but variables can also contain letters and a variety of other things.
The data can be stored in the memory.
These are called variables.
Declaring Variables
There is a simple rule for declaring the variables mentioned earlier in C#.
[Type] [Variable name];
In C#, you can declare a variable by specifying the type followed by the variable name.
Example:
int number; string name;
You can also write the initial value, setting it on a single line like this:
[Type] [Variable name] = value;
Example:
int number = 10; string name = "James";
Sample code:
using System; namespace CSharp_Variable_Sample { public class Program { public static void Main(string[] args) { //Declare int number; string name; // int number2 = 100; string name2 = "James"; Console.WriteLine("Number: {0}", number2); Console.WriteLine("Name: {0}", name2); } } }
Output
Number: 100
Name: James