Var keyword in C#: Best Practices and Examples

VAR Keyword in C#
VAR Keyword in C#

Introduction: var keyword in C#

In C# 3.0, the var keyword was introduced to declare an implicit type local variable that could hold any data. However, it’s important to remember that when using var, you must ensure the variable is assigned a value during declaration.

In simpler terms, var lets us create a variable without deciding its type beforehand. It’s like telling the compiler, “Hey, you decide the type based on what value I assign to this variable.” However, it’s important to note that when we declare a variable with var, we must also initialize it with a value right at the beginning.

var keyword in C#
var variable in C#

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

Advantages of var keyword in C#

The var keyword in C# offers several advantages in various scenarios:

  1. Handling Unknown Types: var is useful for holding the result of a method when the exact type is unknown, such as with anonymous methods, LINQ expressions, or generic types. It allows for more flexibility when working with dynamic or changing data.
  2. Type Safety: Despite being dynamically typed, var is still type-safe. The value assigned to a var variable is known to the compiler at compile time, which helps prevent potential runtime type-related issues. It enhances code stability and reliability.
  3. Elimination of Boxing and Unboxing: var eliminates the need for explicit boxing and unboxing operations. It automatically assigns the appropriate type without requiring explicit conversions, leading to improved performance and efficiency.
  4. Readability Improvement: Using var can enhance code readability, especially when dealing with complex or lengthy class or struct names. It provides a shorthand way of declaring variables, making the code more concise and focused without sacrificing clarity.
  5. Enhanced Tooling Support: Visual Studio shows IntelliSense when working with var because the compiler can determine the type of the assigned variable at compile time. It enables advanced IDE features such as code completion, IntelliSense, and better error detection and correction.

Limitation of var variable in C#

The following are the limitations of using the var variable in C#.

01. var variable must initialize in the same statement

When using the var keyword to create a variable in C#, it is important to declare and initialize the var variable in the same statement. It ensures that the code compiles correctly and avoids any compile-time errors. Additionally, it is worth noting that a 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#

02. The var variable cannot be initialized with the null value

The var variable cannot be initialized with a null value. If we attempt to assign null to a var variable, it will result in an error message being thrown.

 static void Main(string[] args)
        {
          var num = null; // Error
                         
        }

Once we execute the above code statement, we will get the following error message.

Error: Cannot assign <null> to an implicitly-typed variable
var variable with null value in c#
var variable assigned with the null value.

03. The var variable can’t declare at the class level

Due to its local scope, the var variable cannot be declared at the class level. In other words, var or implicitly typed variables are limited to being declared and used within a specific local method and cannot have a broader scope that extends to the entire class.

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 code statement.

The contextual keyword 'var' may only appear within a local variable declaration or in script code.

04. 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
        }

    }

05. Var type can’t be changed once the value has been initialized

Once a var variable is initialized with a specific type, it cannot be changed to a different type. For example, if we assign an integer value to a var variable, it will remain an integer and cannot be reassigned with a string value. The var variable will always retain the type it was originally assigned, ensuring type consistency throughout its usage.

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

Overall, the var keyword offers flexibility, type safety, improved performance, code readability, and enhanced tooling support, making it a valuable choice in appropriate situations.

FAQs

Q: 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.

Q: 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.

Q: How is the var keyword different from explicit type declarations?

Unlike explicit type declarations, where the data type is explicitly specified, the var keyword enables developers to declare variables without explicitly defining their types. The compiler infers the type based on the assigned value.

Q: Can I use var for all variable declarations in C#?

While var offers flexibility, it is not suitable for all scenarios. It is primarily used when the type is evident from the assigned value, such as anonymous types, LINQ expressions, or generic types. For cases where the type is not evident, explicit type declarations are recommended.

Q: Does var affect performance in C#?

No, the var keyword itself does not impact performance in C#. It is a compile-time feature that only affects code readability and type inference. The performance is determined by the actual operations performed on the variables, not by var.

Q: Can I change the type of a var variable after initialization?

No, once a var variable is initialized with a specific type, it cannot be changed to a different type. The var variable will retain its initial type throughout its usage.

Q: Can I change the type of a var variable after initialization?

While var provides convenience, it’s important to ensure that the assigned value has a clear and unambiguous type. Additionally, var cannot be used for variable declarations without initialization, as the compiler requires an assigned value to infer the type.

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

 

Shekh Ali
3 1 vote
Article Rating
Subscribe
Notify of
guest

6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments