In this post, We’ll go through the var keyword in C#

var keyword in C#
In C# 3.0, the var keyword was introduced to declare an implicit type local variable that could hold any type of data.
At the time of declaration, the variable declared as var must be initialized.
In simple words, the var keyword in C# is used to declare a variable whose type is not pre-decided.
By using var, we are supposed to give full control to the C# compiler to determine the data type of the local variable.

The visual studio shows intelligence in the above graphic because the type of variable assigned is known to the compiler at compile time.
The following are the implicitly and explicitly typed variables declaration in C#.
class Program
{
static void Main(string[] args)
{
var a = "Hello"; // Implicit type
string b = "Hello"; // Explicit type
Console.WriteLine($" a : {a} , Type {a.GetType()} ");
Console.WriteLine($" b : {b} , Type {b.GetType()} ");
}
}
// Output:
// a : Hello , Type System.String
// b : Hello , Type System.String
In the above example, the var variable a will be treated as a string based on the right-side value “Hello”;
Limitation of var variable in C#
The following are the limitations of using the var variable in C#.
var variable must initialize in the same statement
While creating a var variable, we must make sure that the variable is declared and initialized in the same statement to avoid the compile-time error.
The var variable cannot be initialized with a null value.
Let’s understand using the following example.
static void Main(string[] args)
{
var num; // Error
num = 10;
}
The above statement will throw an error message because the var variable “num” is not initialized in the same statement.
error: Implicitly-typed variables must be initialized

The var variable cannot be initialized with the null value
The var variable can’t be initialized by the null. It will throw an error message if we assign the null value to the var variable.
static void Main(string[] args)
{
var num = null; // Error
}
Once we execute the above statement, we will get the following error message.
Cannot assign <null> to an implicitly-typed variable

The var variable can’t declare at the class level
We can’t declare the var variable at the class level because the scope of the var or the implicitly typed variable is local.
class Program
{
// Can't declare var variable at the class level
var num = 10; // error
}
We will get the following error message once we execute the above statement.
The contextual keyword ‘var’ may only appear within a local variable declaration or in script code
The var variable can’t pass as a function parameter
We will get a compile-time error if we pass the var variable as a function parameter.
class Program
{
public void Print(var obj) // compile time error
{
// Code
}
}
Type can’t be changed once the value has been initialized
We can’t change the type of the var variable once it has been initialized.
That means if we assign an integer to a var variable then it doesn’t allow us to assign the string value to the same variable.
It will always consider an integer type thereafter.
static void Main(string[] args)
{
var num = 10; //var 'num' has become of integer type
num = num + 20; // No error as '20' is an integer type
num = "Test"; // Compile time error as 'num' is an integer type
}
We will get the compile-time error if we change the value from integer to string type.

When to use the var keyword in C#?
we can use the var keyword in for loop, foreach loop, using statements, anonymous types, LINQ, etc.
Following are the examples of using the var keywords.
Using var keyword to declare anonymous Types
The var keyword is used to hold anonymous types. Following are the program to create and hold an anonymous type.
using System;
namespace AnonymousType
{
class Program
{
static void Main(string[] args)
{
//using "var" with anonymous type
var employee = new { EmpId =101 , Name = "Shekh Ali" };
Console.WriteLine($"EmpId: {employee.EmpId} Name: {employee.Name} ");
Console.ReadKey();
}
}
}
// Output
// EmpId: 101 Name: Shekh Ali
Using “var” in foreach loop and LINQ query
Following are the example of using the var keyword in foreach loop and in LINQ query.
using System;
using System.Collections.Generic;
using System.Linq;
namespace varExample
{
class Program
{
static void Main(string[] args)
{
// List of numbers
List<int> Numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//using "var" in LINQ query to hold even numbers.
var EvenNumbers = Numbers.Where(num => num % 2 == 0);
//using "var" in foreach loop.
foreach (var number in EvenNumbers)
Console.WriteLine(number);
Console.ReadKey();
}
}
}
// OutPut
// 2
// 4
// 6
// 8
// 10
var in using statement
Let’s create a text file “HelloWorldFile.txt” with “Hello World” in D drive.
The following is the code snippet of using var keyword in using statement.
using System;
using System.IO;
namespace varExample
{
class Program
{
static void Main(string[] args)
{
// "var" in using statement
using (var str = new StreamReader(@"D:\HelloWorldFile.txt"))
{
Console.WriteLine(str.ReadLine()?? "Empty file");
}
Console.ReadKey();
}
}
}
// Output:
// Hello World
Use of var keyword in for loop
A var keyword can be used in the for loop statement.
using System;
using System.IO;
namespace varExample
{
class Program
{
static void Main(string[] args)
{
// "var" in for loop statement
for (var index = 1; index <= 5 ; index ++)
{
Console.WriteLine(index);
}
Console.ReadKey();
}
}
}
// Output:
// 1
// 2
// 3
// 4
// 5
Advantage of using var keyword in C#
The following are the advantages of using the var keywords in C#.
-
- var is used to hold the result of a method whose type is not known such as an anonymous method, LINQ expressions, or generic types.
- var is type-safe, the value assigned to the var variable is known by the compiler at the compile time which prevents any issue at the runtime.
- var does not require boxing and unboxing.
- Improve focus on readability of code, It is a shorthand way of declaring a var when the class or struct names are very long.
- Visual Studio shows the intelligence because the type of variable assigned is known to the compiler at the compile time.
What is the use of the var keyword in C#?
The var keyword is used to declare implicit type local variables in C#.
The Implicitly typed local variables are strongly typed, and their types are determined by the compiler at run time by the value stored in them.
Where the var keyword can be used in C#?
The var keyword can be used in the for loop, foreach loop, using statements, anonymous types, LINQ, and other places.
Summary
In this article, we discussed the var keyword in C# with multiple examples.
I hope you enjoyed this post and found it useful. In case you have any doubt, please post your feedback, question, or comments.
Articles to Check Out
-
- C# Abstract class Vs Interface
- C# Array vs List: When should you use an array or a List?
- Generic Delegates in C# With Examples
- IEnumerable Interface in C# with examples
- Constructors in C# with Examples
- C# Private constructor
- C# Enum | How to Use enumeration type in C#?
- Properties In C# with examples
- Multithreading in C#
- IEnumerable Interface in C# with examples
- C# List Class With Examples
- C# Monitor class in multithreading
- C# Struct vs Class
- C# Dictionary with Examples
I think that is among the so much vital information for me.
And i am satisfied studying your article. However should observation on some general issues, The web site style is wonderful, the articles is truly excellent : D.
Excellent job, cheers
Thanks 🙂
Excellent post. I was checking constantly this blog and I
am impressed! Very useful information particularly the last
part 🙂 I care for such info a lot. I was seeking this particular info for
a very long time. Thank you and best of luck.
Howdy! This post couldn’t be written any better!
Reading this post reminds me of my previous room mate!
He always kept chatting about this. I will forward this write-up to him.
Pretty sure he will have a good read. Thank you for sharing!
Good information. Lucky me I ran across your website by
accident (stumbleupon). I’ve book marked it for later!
Wow that was odd. I just wrote an extremely long comment but after
I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Anyhow, just wanted to say superb blog!