In C#, it is possible to define a local variable without explicitly mentioning its data type. The var keyword in C# is employed for declaring implicitly typed local variables. The compiler in C# deduces the variable types based on the assigned values.
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 consider an illustration. In this case, we've generated local variables of integer, string, and array data types.
C# Implicit Typed Local Variable 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:
20
hello world
3