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

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

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...