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

Models in ASP.NET MVC

Models in ASP.NET MVC Explained A model is a class that contains the business logic of your application. It also used for accessing data from the database. The model class does not handle directly input from the browser. In MVC, it is the Controller that handle input from the browser directly and process the request by receiving data from the model and pass it back to view as response. It does not contain any HTML code either. It is a best practice but not mandatory for developers to not have any communications with the view directly, models should only contain a POCO ( Plain Old CLR Objects ) classes. All processing logic and communication with the view should be handled by another layer called Viewmodels. Models are also refers as objects that are used to implement conceptual logic for the application. A controller interacts with the model, access the data, perform the logic and pass that data to the view. Note that it is not mandatory, but it is a good programming...

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...