Variables in C# are the same as variables in mathematics. Before we understand what is a variable, let's understand the expressions. The followings are examples of expressions.
10 + 20
5 * 2
10/2
The result of the above expressions are fixed e.g. 10 + 20 = 30, 5 * 2 = 10 and
10/2 = 5. Now, consider the following expressions.
x + 20
y * 2
z/2
The result of the above expression depends on the value of x, y and z.
For example, if x = 5 then the result of x + 20 would be 25 and if
x = 20 then the result of x + 20 would be 40. In the same way, the
result of y * 2 depends on the value of y and the result of z/2
depends on the value of z. Here, x, y, z are called
variables because their values can be changed.
The same concept is used in C#. In C#, a variable stores a value of the specific data type. It can store a
numeric, char, string, or other types of value. You can declare and assign a value to a variable like
int x = 5; where int is the data type, x is the name of a variable,
= is an operator that assigns the value to a variable, and 5 is the integer value
assigned to a variable x.
<data type> <variable name> = <value>;
The following declares and initializes a variable of an int type.
int num = 100;
Above, int is a data type, num is a variable name (identifier). The =
operator is used to assign a value to a variable. The right side of the = operator is a value
that will be assigned to left side variable. Above, 100 is assigned to a variable num.
The following declares and initializes variables of different data types.
int num = 100;
float rate = 10.2f;
decimal amount = 100.50M;
char code = 'C';
bool isValid = true;
string name = "Steve";
The followings are naming conventions for declaring variables in C#:
- Variable names must be unique.
- Variable names can contain letters, digits, and the underscore
_only. - Variable names must start with a letter.
- Variable names are case-sensitive,
numandNumare considered different names. - Variable names cannot contain reserved keywords. Must prefix
@before keyword if want reserve keywords as identifiers.
C# is the strongly typed language. It means you can assign a value of the specified data type. You cannot assign an integer value to string type or vice-versa.
int num = "Steve";
Variables can be declared first and initialized later.
int num;
num = 100;
A variable must be assigned a value before using it, otherwise, C# will give a compile-time error.
int i;
int j = i; //compile-time error: Use of unassigned local variable 'i'
The value of a variable can be changed anytime after initializing it.
int num = 100;
num = 200;
Console.WriteLine(num); //output: 200
Multiple variables of the same data type can be declared and initialized in a single line separated by commas.
int i, j = 10, k = 100;
Multiple variables of the same type can also be declared in multiple lines separated by a comma. The compiler
will consider it to be one statement until it encounters a semicolon ;.
int i = 0,
j = 10,
k = 100;
The value of a variable can be assigned to another variable of the same data type. However, a value must be assigned to a variable before using it.
int i = 100;
int j = i; // value of j will be 100
Variables can be used in an expression and the result of the expression can be assigned to the same or different variable.
int i = 100;
int j = i + 20; // j = 120
i = 200;
j = i + 20;// j = 220
i = 300;
Console.WriteLine("j = {0}", j);// j = 220
In the above example, value of j depends on the value of i. You must re-execute
expression each time you change the value of i; otherwise, value of j would not
change based on the value of i.
In C#, variables are categorized based on how they store their value in memory. Variables are categorized into value type or reference type or pointer type variables.
It is not necessary to specify the specific type when declaring variables. Use the var keyword
instead of a data type.
C# - var
In C#, variables must be declared with the data type. These are called explicitly typed variables.
int i = 100;// explicitly typed variable
C# 3.0 introduced var keyword to declare method level variables without specifying a data type
explicitly.
var j = 100; // implicitly typed local variable
The compiler will infer the type of a variable from the expression on the right side of the =
operator. Above, var will be compiled as int.
The following infers the type from an expression.
int i = 10;
var j = i + 1; // compiles as int
var can be used to declare any built-in data type or a user-defined type or an anonymous type
variable. The following example shows C# compiler infers type based on the value:
static void Main(string[] args)
{
var i = 10;
Console.WriteLine("Type of i is {0}", i.GetType());
var str = "Hello World!!";
Console.WriteLine("Type of str is {0}", str.GetType());
var dbl = 100.50d;
Console.WriteLine("Type of dbl is {0}", dbl.GetType());
var isValid = true;
Console.WriteLine("Type of isValid is {0}", isValid.GetType());
var ano = new { name = "Steve" };
Console.WriteLine("Type of ano is {0}", ano.GetType());
var arr = new[] { 1, 10, 20, 30 };
Console.WriteLine("Type of arr is {0}", arr.GetType());
var file = new FileInfo("MyFile");
Console.WriteLine("Type of file is {0}", file.GetType());
}
Implicitly-typed variables must be initialized at the time of declaration; otherwise C# compiler would give an error: Implicitly-typed variables must be initialized.
var i; // Compile-time error: Implicitly-typed variables must be initialized
i = 100;
Multiple declarations of var variables in a single statement are not allowed.
var i = 100, j = 200, k = 300; // Error: cannot declare var variables in a single statement
//The followings are also valid
var i = 100;
var j = 200;
var k = 300;
var cannot be used for function parameters.
void Display(var param) //Compile-time error
{
Console.Write(param);
}
var can be used in for, and foreach loops.
for(var i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
var can also be used with LINQ queries.
// string collection
IList<string> stringList = new List<string>() {
"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};
// LINQ Query Syntax
var result = from s in stringList
where s.Contains("Tutorials")
select s;