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

Popular posts from this blog

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...