Var Keyword

Var can be of any type, it is simply an alias and its type is determined by the compiler. There is no performance issues with using the var keyword. Var simply makes your programs shorter and easier to read. Please note that you cannot create a new var type.

Basic syntax:

var wholeNumber = 0; 
// is same as: int wholenumber = 0; 
var name; 
// This wont work, it will throw an error.

The name variable “var name;” will throw an error because the compiler doesn’t know what variable type it is, as there is no such type actually exists, it aliases other types. To use the var keyword the variable must be assigned a value at time of creation. To make the name variable work it must be assigned like this:

var name = "Get Coding"; 
// is same as: string name = "Get Coding";

The var keyword can even be used when calling a function that returns a type. This is because the compiler knows the type of the returning variable.

using System; 

namespace GetCoding 
{
   class Program
   {
      static void Main(string[] args)
      {
         var name = GetName(); 
         // Calls GetName() function which returns a string. 
         // var name is a string type.     
      } 

      static string GetName() 
      { 
         return "Get Coding"; 
      }
   }
}

Using the var keyword type is often considered good coding practice and better for maintainability, take the above example, imagine the function GetName was changed to the following:

private string[] GetName() 
{ 
   return new string[] { "Get Coding" }; 
}

now take a look at the following snippet:

static void Main(string[] args) 
{ 
   // because these three variables used the original string return type, 
   // now they will error on build as they are no longer string types, 
   // they are now string[] types. 
   // so no everywhere its declared like this will need to be updated. 
   string name1 = GetName(); 
   string name2 = GetName(); 
   string name3 = GetName(); 
   
   // as this uses the var type, it will now become string[] type 
   // without the need to update.   
   var name4 = GetName(); 
}

This is just one example of a coding practice, another reason for using this, is the var keyword is easier, nicer to read and instantly indicates as a variable.