English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In C#, variables must be declared with a data type. These are called explicitly typed variables.
int i = 100;// Explicit variables
C#3The '.0' introduces the 'var' keyword to declare method-level variables without explicitly specifying the data type.
var j = 100; // Implicitly typed local variables
The compiler will infer the type of the variable from the expression on the right side of the = operator. In this case, 'var' will be compiled as int.
The following types are inferred from expressions.
int i = 10; var j = i + 1; // Compiled as int
The 'var' keyword can be used to declare variables of any built-in data type, user-defined type, or anonymous type. The following example shows how the C# compiler infers the 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, the C# compiler will give an error: Implicitly typed variables must be initialized.
var i; // Compile-time error: Implicitly typed variables must be initialized i = 100;
var does not allow multiple variable declarations in a single statement.
var i = 100, j = 200, k = 300; // Error: var variables cannot be declared in a single statement//The following is 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;