Introduction To Var Datatype In C#

This article introduces us to var datatype in C#.

var Type

  • C# 3.0 adds the interesting behavior of Declaring Local Variables Implicitly. This means that there is no need to mention the data type when declaring a variable. A local variable can be declared implicitly using the var keyword in C#.

  • Declaring local variables implicitly has some restrictions; the variable must be initialized to some expression that can not be null.

    1. var a= 10;   
    2. var z = "Rekha";  
  • The primary reason for its existence is the introduction of anonymous types in C#

  • Another point to stress is that variable inference does not work for class level fields or method arguments or anywhere else other than for local variables in a method.

Advantages

  • Less typing with no loss of functionality

  • Increases the type safety of your code. A foreach loop using an iteration variable which is typed to var will catch silently casts that are introduced with explicit types

  • Makes it so you don't have to write the same name twice in a variable declaration.

  • Some features, such as declaring a strongly typed anonymous type local variable, require the use of var

Example 1

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Text;   
  5.    
  6. namespace Namesp1  
  7. {   
  8.     class Program   
  9.     {   
  10.         static void Main(string[] args)   
  11.         {   
  12.             var x = Convert.ToInt32(Console.ReadLine());   
  13.             var y = Convert.ToInt32(Console.ReadLine());   
  14.             Console.WriteLine("The Sum Is : " + (x + y));   
  15.         }   
  16.     }   
  17. }   

Example 2

  1. using System;   
  2. namespace ConsoleApplication1   
  3. {   
  4.     class A   
  5.     {   
  6.         public static void Main()   
  7.         {   
  8.             int sum = 0;   
  9.             int[] arr = new int[10];   
  10.             for (int i = 0; i < 10; i++)   
  11.             {   
  12.                 arr[i] = i;   
  13.             }   
  14.             foreach (var x in arr)   
  15.             {   
  16.                 Console.WriteLine("Value is: " + x);   
  17.                 sum =sum + x;   
  18.             }   
  19.             Console.WriteLine("Sum of array elements is : " + sum);   
  20.         }   
  21.     }   
  22. }  

Output
 

VarOutput.bmp