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.

var keyword in C#
var variable in C#

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.

Advantage of using var keyword in C#

The following are the couple of advantage of using var keyword 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 have understood the restriction and advantage of using the var keyword in C#.

I hope you enjoyed this post and found it useful. Thanks for visiting.

2 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

Leave a Reply

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

7 − four =