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
1 2 |
var myVariable; //illegal var myVar2 = "abc"; // legal statically defined |
while in Javascript this will be ok, since it is dynamically typed.
1 2 |
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:
1 |
var person = new { Name = "Hello", Age = 99 }; |
One can also use var when using LINQ
1 2 3 |
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.
1 2 3 |
IEnumerable<string> 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.
1 |
var list = new List<MySuperLongNameObjectThatShouldNotBeAllowed>(); |
In conclusion:
- Javascript var != C# var
- Anonysmous Type requires var
- var can be used in LINQ return type
- Use var to avoid duplicating declaration names of type
Leave A Comment