What to use: var or type of object name?

It is a question that when programming I always wonder: what to use when we write code:

var myFiles = Directory.GetFiles(fullPath); 

or

 string[] myFiles = Directory.GetFiles(fullPath); 

var is new and is an implicitly typed local variable, so we can only use it locally, and it has rules like it cannot be null, etc., but I wonder if we got any advantage using it "fine".

The "usually" section does not talk about anonymous types , Initializers of objects and collections and query expressions , where it was intended to be used by an anonymous var object, so I mean ... like in the example above.

What do you think?

+50
Oct. 25 '08 at 19:21
source share
8 answers

Besides the obvious use of var with LINQ, I also use it to shorten declarations of hairy variables for readability, for example:

 var d = new Dictionary<string, Dictionary<string, Queue<SomeClass>>>(); 

In general, I get some comfort (due to the lack of a better word) from static text input, which makes me reluctant to abandon it. I like the feeling that I know what I do when I declare a variable. Declaring a variable doesn't just tell the compiler something that tells the person something reads your code.

Let me give you an example. Suppose I have a method that returns a List<string> . This code is certainly correct, and I think that 90% of C # developers will probably write it:

 List<string> list = MyMethod(); 

Obviously right? In fact, here you could easily use var .

Right. But this version of the code does not just declare a variable, it tells me what the one who wrote it intends to do:

 IEnumerable<string> list = MyMethod(); 

The developer who wrote this code tells me: "I'm not going to change this list, and I will not use the index to access its members. All I am going to do is iterate over it." This is a lot of information that can be found in one line of code. This is what you will refuse if you use var .

Of course, you will not refuse if you do not use it in the first place. If you are such a developer who would write this line of code, you already know that you will not use var there.

Edit:

I just re-read John Skeet's post, and this quote from Eric Lippert popped up on me:

Implicitly printed locales are just one small way in which you can defocus how to emphasize that.

I think that in many cases the use of implicit typing leaves the implicit. This is normal so as not to stop at anything. For example, I accidentally write a LINQ query, for example:

 var rows = from DataRow r in parentRow.GetChildRows(myRelation) where r.Field<bool>("Flag") orderby r.Field<int>("SortKey") select r; 

When I read this code, one of the things that I think when I read is " rows is IEnumerable<DataRow> ". Since I know that LINQ queries are returned, this is an IEnumerable<T> , and I can see the type of the selected object.

This is the case when that which has not been made explicit. I could only conclude.

Now in about 90% of cases when I use LINQ, it does not matter, one small bit. Since 90% of the time, the following line of code:

 foreach (DataRow r in rows) 

But it’s easy to imagine code in which it would be very useful to declare rows as IEnumerable<DataRow> - a code in which many different types of objects were requested, it was impossible to place a query declaration next to iteration, and it would be useful to be able to check rows for IntelliSense. And this is something, not how.

+59
Oct 25 '08 at 20:58
source share

You will get a huge amount of opinions about this - from "use var everywhere" to "use only var with anonymous types, where you mostly need to." I like Eric Lippert to take on him :

All code is an abstraction. What does the "really" code do to manipulate the data? No. The numbers? Bits? No. Stress? No. Electrons? Yes, but understanding the code at the electron level is a bad idea! The art of coding finds out which right level of abstraction is for the audience.

In a high-level language, there is always this tension between WHAT the code does (semantically) and HOW the code executes it. Service programmers need to understand how and what if they go to be successful in making changes.

The whole point of LINQ is that it massively cancels the “how” and massively emphasizes the “what”. From using an understanding of the query, the programmer says to the future of the audience, “I believe that you should not care about how this result set is computed, but you should really care about the semantics of the result set.” They bring the code closer to the business process and further from the bits and electrons that make it go.

Implicitly typed local residents are just one small way in which you can discount how and thereby emphasize which ones. Is this the correct estimate in a particular case? Therefore, I tell people that if knowledge of this type is relevant and its choice is crucial for the continuation of the method, then do not use implicit typing. Explicit text input says: "I tell you how it works for some reason, pay attention." Implicit typing says "it doesn't matter whether this thing is a list or a Client [], what matters is that it is a collection of clients."

Personally, I am not inclined to use it if the type is not obvious enough - where I include LINQ queries as “fairly obvious”. I would not do this for Directory.GetFiles , for example, since it is not quite obvious that returns string[] instead of (say) a FileInfo[] (or something else completely) - and this is of great importance for what you do it later.

If there is a constructor call on the right side of the assignment operator, I have a much better chance of going with var : it is clearly obvious what type it will be. This is especially convenient with complex typical types, for example. Dictionary<string,List<int>> .

+41
Oct 25 '08 at 19:25
source share

Personally, I use var in only two places:

  • With anonymous types i.e. LINQ-related (where var is required in some cases)
  • When an operator declares and constructs a particular type of the same type

T. This is an example of point 2:

 var names = new List<String>(); 

Edited : this is in response to a question from John Skeet.

This answer has actually been simplified. Basically, I use var, where type:

  • Unnecessary to know (not many places)
  • Unable to know (LINQ, anonymous types)
  • Otherwise, known or cleared from code

In the case of the factory method, where all you need to know in the place where you are writing the code is that the object you are returning is a descendant of some type and some type has a static factory>, then I would use var. Like this:

 var connection = DatabaseConnection.CreateFromConnectionString("..."); 

The above example is a real example of my code. It is clear, at least for me and the people who use this code, this connection is a descendant of DatabaseConnection, but the exact type is not needed either to understand the code or to use it.

+11
Oct. 25 '08 at 19:30
source share

I tried the "use var everywhere" style ... and that is why I did not continue to use it.

  • Degraded readability at times
  • Intellisense limits after =
  • Typing "var" really wasn't much shorter than typing "int", "string", etc., especially with intellisense.

Having said that, I am still using it with LINQ.

+9
Oct 25 '08 at 19:41
source share

This post has some good recommendations on when to use an interface like var or object types.

+3
Oct 25 '08 at 20:15
source share

Based on the land of functional programming, where text input rules determine the day, I use var for all local residents, where possible.

In Visual Studio, if you ever wonder what type of localhost is all you need to do is move your mouse over it.

+3
Oct 26 '08 at 4:21
source share

I usually use var everywhere, but my colleagues said that they stop, it is less readable for us. Therefore, I now use var only for anonymous types, LINQ queries, and where there is a constructor on the right side.

+3
Dec 13 '08 at 16:41
source share

It seems interesting to me to note how this is usually handled in Haskell. Thanks to Curry-Howard isomorphism, you can define the (most common) type of any expression in Haskell, and thus type declarations are essentially not needed anywhere, with a few exceptions; for example, sometimes you intentionally want to limit the type to something more specific than it would be inferred.

Of course, what is required and what is recommended is not the same thing; in practice, the convention seems to be that top-level definitions always have type declarations, while localized definitions do not contain type declarations. This, apparently, provides a good balance between the obviousness and readability of the definition as a whole, as opposed to brevity for the readability of local “auxiliary” or “temporary” definitions. If I understand correctly, you cannot use var to define a "top level" (for example, a method or a global function), so I assume that it means "use var wherever you can" in C # World. Of course, typing " int " is the same number of keystrokes as " var ", but most examples will be longer than this.

+1
Oct. 25 '08 at 21:46
source share



All Articles