var keyword in C#-Restrictions and Advantage of using var variable

In this article, we will understand the var keyword in C#.

var keyword in C#

The  var  keyword was introduced in C# 3.0 to declare an implicitly typed of local variable to hold any type of data.
In implicitly typed variables, the type of the variable declared is decided by the compiler at the compile-time based on the type of the value that the variable is initialized with.
The variable declared as var is mandatory to initialize at the time of declaration.

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.

var keyword in C#
var variable in C#

In the above image, we can see that the visual studio shows the intelligence because the type of variable assigned is known to the compiler at the 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

var variable declaration in c#

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

var variable with null value in c#
var variable assigned with the null value.

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 as 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.

var value initialization
 Note  : It is not recommended to always declare the local variables as var instead of defining the actual data types because for the var variable the compiler does extra work to determine the actual type based on the value assigned to the variable.

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 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

var 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.

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.

Thanks for visiting.

6 Replies to “var keyword in C#-Restrictions and Advantage of using var variable”

  1. 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

  2. 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.

  3. 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!

  4. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *