C# Var Keyword

In c# 3.0, the var keyword has been introduced to declare the implicitly typed local variables without specifying an explicit type. The type of local variables will automatically determine by the compiler based on the right-side value of the initialization statement.

 

The following two declarations are functionally equivalent in c#.

 

var x = 50; // Implicitly typed
int y = 50; // Explicitly typed

The above two declarations are functionally equivalent. As discussed, the compiler will automatically infer the type “integer” to the variable x based on the right-side value 50.

C# Var Keyword Example

Following is the example which will show the various ways of declaring the implicitly typed local variables with var keyword in c#.

 

using System;

namespace TutlaneExamples
{
    class Program
    {
       static void Main(string[] args)
       {
          var i = 100;
          Console.WriteLine("i value: {0}, type: {1}", i, i.GetType());
          var j = "Welcome to Tutlane";
          Console.WriteLine("j value: {0}, type: {1}", j, j.GetType());
          var k = true;
          Console.WriteLine("k value: {0}, type: {1}", k, k.GetType());
          var l = 20.50;
          Console.WriteLine("l value: {0}, type: {1}", l, l.GetType());
          Console.ReadLine();
       }
    }
}

If you observe the above example, we declared and initialized the implicitly typed local variables with different values. The compiler will automatically determine and assign the most appropriate type based on the assigned value.

 

When we execute the above example, we will get the result as shown below.

 

i value: 100, type: System.Int32
j value: Welcome to Tutlane, type: System.String
k value: True, type: System.Boolean
l value: 20.5, type: System.Double

In the above example, we used var keyword to declare the variables at the method level, but we can also use the var keyword in for, foreach and using statements like as shown below.

 

**** for loop ****
for (var i = 1; i < 10; i++)
{
   // your code
}
**** foreach loop ****
foreach (var item in list)
{
   // your code
}
**** using statement ****
using (var sr = new StreamReader(@"D:\Test.txt"))
{
   // your code
}

In many cases, the use of var is optional, but while working with the anonymous types, we need to declare the variables with var as shown below to access the properties of an object, and it’s a common scenario in LINQ query expressions.

 

// Create anonymous type object
var userInfo = new
{
   Id = 1,
   Name = "Suresh Dasari",
   IsActive = true
};
// Access anonymous type object properties
Console.WriteLine("Id:" + userInfo.Id);
Console.WriteLine("Name:" + userInfo.Name);
Console.WriteLine("IsActive:" + userInfo.IsActive);

C# Var Variable Restrictions

In c#, while creating implicitly-typed local variables, we need to ensure that the variable is declared and initialized in the same statement; otherwise, we will get a compile-time error. The variable cannot be initialized with a null value.

 

var x = 10; // valid
var y; y = 10; // Error: Implicitly-typed variables must be initialized
var z = null; // Error: Cannot assign null to implicitly typed variable

In c#, implicitly-typed variables cannot be used as method parameters and we should not initialize multiple implicitly-typed variables in the same statement.

 

var x = 10, y = 20, z = 30; // Invalid: Compile-time Error
var x = 10; // valid
var y = 20; // valid
var z = 30; // valid
// var variable as function Parameter
void GetDetails(var x) // Invalid: Compile-time error
{
// your code
}

Same way, we are not allowed to use implicitly-typed variables in initialization expressions like as shown below.

 

int x = (x = 20); // valid
var y = (y = 20); // invalid

C# Var Keyword Overview

Following are the important points which we need to remember about var keyword in c#.

 

  • var keyword is useful to declare the implicitly-typed local variables without specifying an explicit type.
  • In c#, the type of implicitly-typed local variables will automatically determine by the compiler based on the right-side value of the initialization statement.
  • The var variables must be declared and initialized in the same statement.
  • We are not allowed to assign a null value to the implicitly-typed local variables.
  • Cannot initialize the multiple implicitly-typed variables in the same statement.
  • var is not allowed to use as a field type at the class level.