In this section we’re assuming you’re already familiar with the data types in C#.
In C# we have two ways on declaring the type of a variable.
-
Explicitly: This is done when we explicitly set the type of a
variable to one of those prebuilt primitive types (string, int, short,
double etc.) or custom data types that we create via classes.
Example:
int age = 20;
Here the variable’s type is int and so we can only assign integer values to this variable.
-
Implicitly: The second way of setting the data type of a variable
is implicit and is done via the `var` keyword.
To create an implicit variable, instead of assigning a data type for a variable, we set the keyword var as the replacement for the data type on a variable.
For example:
var iii = 2000;
In situation like this, the compiler will automatically find the data type of the variable by looking at the value that we assigned to that variable.
Notes:
-
When declaring a variable via the `var` keyword, we must
initialize the variable right away where it’s being declared. Otherwise
the compiler will throw an error. This is because the compiler uses the
value of a variable to speculate the type of that variable. So if we
skip the initialization here, there’s no way for the compiler to figure
out what data type the variable should be set to. -
Also when the compiler set the type for a variable and fixed it,
it can’t have another type anymore. This means if we assigned an integer
value to a variable that is declared via `var` keyword, the compiler
will set the type `int` for that variable and from that moment onward,
we cannot assign a value of different type (like string or char
etc.).
Example:
using System;
namespace quickExample
{
class Program
{
static void Main(string[] args)
{
var c = 'A';
var i = 23;
var st = "John Doe";
Console.WriteLine(c);
Console.WriteLine(i);
Console.WriteLine(st);
}
}
}
Output:
A
23
John Doe
In this example the variable c is assigned the value 'A' and so it is considered of type char. The second variable i is assigned the value 23 so the compiler consider this variable of type int. The last variable st is assigned the value "John Doe" and so it is considered of type String.
Again, after the compiler set the type for each variable, we can’t assign a value of different type to those variables. If we do so, the compiler will throw an error instead of compiling the program.