X

C# var keyword misconceptions

dotnet C#

Lots of developers confuse the var keyword in C# with JavaScript.
The var keyword was introduced in C# 3.0, and it is basically implicitly defined but is statically defined, var are resolved at compile time not at run-time.

The confusion is there also a var keyword in JavaScript, but in JavaScript var is dynamically defined.

Example:

In C# this would be illegal

 var myVariable; //illegal
 var myVar2 = "abc"; // legal statically defined

while in Javascript this will be ok, since it is dynamically typed.

var myVariable; //legal in javascript, defined as null
var myVar2 = "abc"; //legal in javascript

In C# one place that you are required to use var is when using Anonymous Types, that is when the compiler generates the internal type.

Example:

 var person = new { Name = "Hello", Age = 99 };

One can also use var when using LINQ

  var hungry_hippos = from p in Animals where p.Name.Contains("hungry") select p.Name;
  foreach(var name in hungry_hippos)
     Console.WriteLine(name);

The above statement returns us a List of string names, the downside to this is if someone is reading this code they may think its a list of Animals that is returned, one can also define the return type in the foreach statement to make it clear or in LINQ. This may create a more readable code but I think having var also does the job well once you get comfortable using it.

  IEnumerable hungry_hippos = from p in Animals where p.Name.Contains("hungry") select p.Name;
  foreach(string name in hungry_hippos)
     Console.WriteLine(name);

Another place that var comes in handy is when defining a type to avoid repetition.

var list = new List();

In conclusion:

  1. Javascript var != C# var
  2. Anonysmous Type requires var
  3. var can be used in LINQ return type
  4. Use var to avoid duplicating declaration names of type
Categories: .NET
Tags: csharpdotnet
Taswar Bhatti:
Related Post