var in C#

Using var keyword, you can declare and initialize variable of any type.  By the initialization value, the type of variable (created using ‘var’ keyword) would be decided.

Let us see an example


var varString = "Hello World";

var varInt = 32;

Console.WriteLine(varString.GetType()); // Will print System.String

Console.WriteLine(varInt.GetType()); // Will print System.Int32

In the above code snippet, we are declaring couple of variables varString, varInt and assigning string value (“Hello World”) , integer value(32) respectively.

When you probe the type of the objects, varString is of type String – just because we have initialized with string value and varInt is of type Int32 – for the same reason we have initialized with integer value.

Offers compile type safety:

Once the variable created and initialized using ‘var’ keyword, the type of the object cannot be changed.

Let us extend the previous example.  In the above code snippet, add the below statement

varString = 32;

When I try to assign an integer value, say 32, to varString variable – it will throw the error saying “Cannot implicitly convert type ‘int’ to ‘string’”

The reason why we are getting the above error is that – whenever we initialize the ‘var’ variable with a value, the type of var variable is set at that point and cannot be changed after that. In the above example, the type of ‘varString’ is set to string when we executed the statement


var varString = "Hello World";

Then, you might wonder about the necessity of ‘var’ keyword – when you can declare the variable with type directly.

For example,

We can declare


string someString = "Hello World";

instead of


var someString = "Hello World";

You might think the first statement (using string type directly) is much clearer than confusing var keyword statement.

Yes, what you think is correct. However, there are some places where declaring types using var becomes necessary.

Let us discuss about a scenario.

You have a list of employee objects on which you have to filter based on some criteria and take out few properties and do calculations on the same and return a new list. Let us try to do that.

  1. Declare a new class ‘Employee’ – this type is used to store the employee related information
class Employee
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public decimal Salary { get; set; }
 
    }

2. Create few employee objects and add it to the list

List employees = new List();
            Employee e1 = new Employee()
            {
                Id = "1",
                Name = "Mugil",
                Salary = 4000
            };
            Employee e2 = new Employee()
            {
                Id = "2",
                Name = "Skeet",
                Salary = 10000
            };
 
            Employee e3 = new Employee()
            {
                Id = "3",
                Name = "Gayathiri",
                Salary = 6000
            };
            employees.Add(e1);
            employees.Add(e2);
            employees.Add(e3);

3. Filter the employee objects based on criteria and create a new list of anonymous type

var employeeNameSalaries = from ens in employees
                                       where ens.Salary > 5000
                                       select new { Name = ens.Name, Salary = ens.Salary, Tax = (ens.Salary * 0.01m) };

In the above statement, we are filtering the employee objects and create a new anonymous type with Name, Salary and Tax as its properties. In this case, it becomes necessary to use the ‘var’ keyword for referring to the anonymous type. Without var keyword, we may not be able to refer the anonymous type.

4.      Print the values


foreach ( var employeeNameSalary in employeeNameSalaries)
            {
                Console.WriteLine("Name:"+employeeNameSalary.Name);
                Console.WriteLine("Salary:"+employeeNameSalary.Salary);
                Console.WriteLine("Tax:"+employeeNameSalary.Tax);
            }

Using ‘var’ keyword offers type safety at compile time.

To conclude, declaring var keyword for simple types is not necessary(a syntactic sugar) but usage of var becomes necessary when you are dealing with anonymous types.

Please note that the var keyword is not to be confused with dynamic variable- where we can change the type of the object after initialization. The dynamic keyword will be discussed in later article.


Posted

in

by

Tags: