find and solve || findandsolve.com
Please wait.....

C# Var Keyword

The var keyword has been introduced in c# 3.0 programming language 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 given below two declarations are functionally equivalent in c#.

var a = 20; // Implicitly typed

int b = 20; // Explicitly typed

In the given above two declarations are functionally equivalent. As discussed, the compiler will automatically infer the type integer to the variable a based on the right-side value 20.


C# Var Keyword Example


The given below example will show the various ways of declaring the implicitly typed local variables with var keyword in c#.

using System;

namespace FindAndSolve
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = 100;
            Console.WriteLine("a value: {0}, type: {1}", a, a.GetType());
            var b = "Welcome to Tutlane";
            Console.WriteLine("b value: {0}, type: {1}", b, b.GetType());
            var c = true;
            Console.WriteLine("c value: {0}, type: {1}", c, c.GetType());
            var d = 20.50;
            Console.WriteLine("d value: {0}, type: {1}", d, d.GetType());
            Console.ReadLine();
        }
    }
}

Output




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


for (var i = 1; i < 10; i++)

{
   // your code
}
**** foreach loop ****
foreach (var item in data)
{
   // your code here
}
**** using statement ****
using (var strReader= new StreamReader(@"D:\demo.txt"))
{
   // your code here
}


In many cases, the use of var is optional, but while working with the anonymous types, you 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
{
   FirstName = "Sylvia",
   LastName = "Neupane",
   Status= true
};
// Access anonymous type object properties
Console.WriteLine("Id:" + userInfo.FirstName);
Console.WriteLine("Name:" + userInfo.LastName);
Console.WriteLine("IsActive:" + userInfo.Status);


C# Var Variable Restrictions


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

var a= 10; // valid

var b; b= 10; // Error: Implicitly-typed variables must be initialized
var c= null; // Error: Cannot assign null to implicitly typed variable


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


var a= 10, b= 20, c= 30; // Invalid: Compile-time Error

var a= 10; // valid
var b= 20; // valid
var c= 30; // valid
// var variable as function Parameter
void GetDetails(var x) // Invalid: Compile-time error
{
// your code
}


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

int a= (a= 20); // valid

var b= (b= 20); // invalid

 

C# Var Keyword Overview


  • var keyword is useful to declare the implicitly-typed local variables without specifying an explicit type.
  • In c# programming language, 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.
  • You 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.