Skip to main content

The keyword ‘var’ in C#?

The keyword ‘var’ what it is in C#?

The var keyword was introduced C# 3.0, used to declare the implicitly typed local variables without specifying an explicit type and the type of local variables will automatically be determined by the compiler based on the right-side value of initialization statement.

 

The two declarations below are functionally equivalent in C#.

 

// Implicitly typed

var x = 50;

// Explicitly typed

int y = 50;

As discussed above, the compiler will automatically infer the type “integer” to the variable x based on the right side value 50.

 

Var Keyword Example

The examples show the various ways of declaring the implicitly typed local variables with var keyword in C#.

 

using System;

namespace CsharpnaijaTutorial

{

    class Program

    {

        static void Main(string[] args)

        {

            var i = 100;

 Console.WriteLine("i value: {0}, type: {1}", i, i.GetType());

            var j = "Welcome to Csharp Naija";

 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();

        }

    }

}

 

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

 

We can also use the var keyword in forforeach and using statements as shown in code snippets below

 

            //**** for loop * ***

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

            {

              // code segment

            }

            //**** foreach loop * ***

            var list = new List<strin>();

            foreach (var item in list)

            {

               // your code

            }

            //**** using statement****

            using (var sr = new StreamReader(@"D:\Test.txt"))

            {

                // your code

            }

Generally, in many cases the use of var is an option but while working with the anonymous types, we must need to declare the variables with var like 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 = "Musa Gadabs",

                IsActive = true

            };

            // Access anonymous type object properties

            Console.WriteLine("Id:" + userInfo.Id);

            Console.WriteLine("Name:" + userInfo.Name);

            Console.WriteLine("IsActive:" + userInfo.IsActive);

 

 

Var Variable Restrictions

In C#, while creating implicitly-typed local variables we need to make sure that the variable is declared and initialized in the same statement otherwise we will get a compile-time error and the variable cannot be initialized with a null value as shown below.

 

     var x = 10; // valid

var y; // not valide: Implicitly-typed variables must be initialized

y = 10; // Error: Implicitly-typed variables must be initialized

var z = null; // Error: Cannot assign null to implicitly typed variable

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

            }

 We are not aslo allowed to use implicitly-typed variables in initializing expressions as shown below.

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

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

 

Important Points

Below are some of the important points which we need to remember about var keyword.

1.     var keyword is useful to declare the implicitly-typed local variables without specifying an explicit type.

2.     The type of implicitly-typed local variables will automatically be determined by the compiler based on the right-side value of the initialization statement.

3.     The var variables must be declared and initialized in the same statement.

4.     We are not allowed to assign a null value to the implicitly-typed local variables.

5.     Multiple implicitly-typed variables cannot be initialized in the same statement.

6.     var is not allowed to use as a field type at the class level.

 

Thank you


Comments