A variable is like a container. It is used to store a value or content. The content it stores is a value and can be any kind of content. A typical example is a bottle of water; it is used to store a type of content called water. The bottle here is the variable
and the value is the water
.
In C#, creating a variable is easy. It is no different from the usual pattern of creating variables in other languages.
As noted earlier, containers (variables) have a specific kind of content (value). For example, a water bottle is used to hold a value of type water. So, for us to create a variable, we must first know the type of content or value it should contain.
The various data types in C# include:
int
, short
, long
, char
, etc.Decimal
true
or false
valuesSo, our variables in C# must contain any of the data types above.
Variable definition is a way of specifying the kind of values our containers should have. It is when we say water should only be stored in this cup and only a bunch of keys should be in a particular box.
It goes like this: data_type variable_name
. See the code snippet below:
int age, yearOfBirth;char gender, initial;float salary, price;bool isDelivered, pending;
In the code snippet above, we created variables such as age
, salary
, isDelivered
, etc., and specified the type of data they should contain. That is variable definition.
This is when we give values to our variables. We must make sure that the value we give to our variables correlates with the variable definition.
The format goes this way: variable_name = value
. See example below:
age = 20;gender = "M";price = 300.00;
We defined variables, initialized them, and printed their values to the console in the code below.
// create classclass Variables{// main methodstatic void Main(){// define variablesint age;char sex;bool isMarried;double salary;int yearOfBirth;// initialize variablesage = 100;sex = 'M';isMarried = false;yearOfBirth = 1921;salary = 1800.50;// print variable values to consoleSystem.Console.WriteLine(age);System.Console.WriteLine(sex);System.Console.WriteLine(isMarried);System.Console.WriteLine(yearOfBirth);System.Console.WriteLine(salary);}}