What is the use of “VAR” keyword in c#

In my opinion, var should be used when either of the following is true:

  1. The type is anonymous (well, you don’t have any choice here, as it must be var in this case)
  2. The type is obvious based upon the assigned expression (i.e. var foo = new TypeWithAReallyLongNameTheresNoSenseRepeating())

var has no performance impacts, as it’s syntactic sugar; the compiler infers the type and defines it once it’s compiled into IL; there’s nothing actually dynamic about it.
============================================================================

var can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this:

var orders = cust.Orders;

I don’t care if Customer.Orders is IEnumerable<Order>ObservableCollection<Order> orBindingList<Order> – all I want is to keep that list in memory to iterate over it or get its count or something later on.

============================================================================

Limitations

Next, we consider some interesting limitations of the var keyword. You can’t assign a var to null. This will result in the CS0825 warning. You also can’t use var as a parameter type or a return value of a method.

============================================================================

Uses

One tip is to use var on generic types. The Dictionary type has verbose syntax—it uses a lot of brackets and letters and a comma. Some code becomes much easier to read when you use var. Var can even make code refactoring easier.

Tip:
If you change a type name with refactoring, a var type local will not need to be changed.

Next, you can use var in a foreach-loop construct. This makes the loop syntax really simple. Simple often means easy to understand.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s