In C#, we can create local variable without specifying its type. The C# var keyword is used to create implicit typed local variables. The C# compiler infers the types of variable on the basis of assigned value.
The var keyword can be used in following context.
- To create local variables inside a method block.
- In loop construct to initialize variable.
- In using statement to store resource reference.
The var keyword has following restrictions.
- It should use to declare and initialize local variable in the same statement.
- It cannot be used to declare class variables.
- It cannot be used to initialize multiple implicitly-typed variables in the same statement.
- It cannot be used in initialization expression. Ex. var a = (a=220);
Let's see an example. Here, we have created integer, string and array type local variables.
C# Implicit Typed Local Variable Example
Example
using System;
namespace CSharpFeatures
{
class ImplicitTypedExample
{
public static void Main()
{
// integer
var a = 20;
// string
var s = "Hello World";
// array
var arr = new[] { 1,2,3};
Console.WriteLine(a);
Console.WriteLine(s);
Console.WriteLine(arr[2]);
}
}
}
Output:
Output
20
hello world
3