0

Duplicate

Use of var keyword in C#
C# - Do you use "var"?
Should I always favour implictly typed local variables in C# 3.0?

Would you prefer to write your code like this:

var myVar = new MyClass();

or

MyClass myVar = new MyClass();

I don't object to use the var keyword in example above; however, in the code below I don't like the usage of var.

var files = Files.GetFiles();

In this example it's not obvious what type variable files is going to be.

What's your preference for using the var keyword?

Community
  • 1
  • 1
Vadim
  • 21,044
  • 18
  • 65
  • 101
  • Please take a look at the related posts before asking. There are already two very good community wiki questions on the subject. – Noldorin Apr 25 '09 at 00:09

4 Answers4

4

I tend to use 'var' in places where I, reading the sourcecode, can infer the type of the variable without having to navigate to other places in the sourcecode.

For example, any time I new up an object:

var c = new Customer();

Or when calling a method in which the return type is clear:

var c = Customers.GetCustomerByID(5);

Also, 'var' must be used in the case of anonymous types:

var t = new { Key = "One", Value = 1 };

And I also use it with LINQ of course:

var q = from c in Customers
        where c.CustomerID == 5
        select c;

In the case above 'q' is of type IQueryable (assuming Customers is an enumeration of Customer objects).

Also 'foreach' statements as well - GREAT please to use 'var':

foreach (var i in intArray) { /* use i */ }

Other examples abound I'm sure - but these cover my most frequent use cases.

Erik Forbes
  • 35,357
  • 27
  • 98
  • 122
1

If it's a situation where either would work (which excludes the anonymous type situation), I try to use whatever will make the code easier to understand in the future. Sometimes that means using var if the usage scope is small or the type being assigned to is unwieldy (e.g., somekind of nested generic) to repeat and adds clutter. I also tend to use var where most people expect to see (e.g. as the declaration of a linq query).

Rob Scott
  • 449
  • 3
  • 4
0

I think it's best to only use var when creating a new object (with new) and with LINQ (of course). That makes the code much easier to understand, IMHO.

Zifre
  • 26,504
  • 11
  • 85
  • 105
0

I use it everywhere I can. I think it makes code far more clean and readable. (Who am I kidding? I just do what resharper tells me to do :)

Much more of that on this SO thread.

Community
  • 1
  • 1
JP Alioto
  • 44,864
  • 6
  • 88
  • 112