In this overview of C#’s var keyword, Justin James explains that var is used in variable declarations instead of a type. He also discusses the differing opinions about what makes var useful.
—————————————————————————————
Welcome to a new Programming and Development series called “Code concepts.” In this series, I intend to walk through a number of topics in detail, and put together a common sense, plain language summary of what you need to know to get started. In many ways, this will feel like a tutorial, but for some topics, there will be less emphasis on the “put tab A into slot B” that you see in so many tutorials, and more of a focus on the ideas.
This format might change, depending on reader feedback. So please let us know what you think of this new series, both positive and negative. Is it too basic, too advanced, or right on target? Are we looking at topics you find interesting? What topics would you like to see covered in future editions? Let us know by posting your feedback in the discussion.
Var keyword
Today, we take a closer look at C#’s var keyword, which was introduced in C# 3.0. I just started reading Essential LINQ by Charlie Calvert and Dinesh Kulkarni. var comes up all of the time in LINQ for reasons discussed below. In the book, there is a brief discussion about var and why it gets used in LINQ; this discussion prompted me to learn more about var, and I am glad that I did. I have been seeing var all over the place for the last year or two, but it wasn’t until I read about it in this book that I had ever seen someone enumerate reasons to actually use it. (By the by, I am only in Chapter 2 of the book, and so far I like it a lot. I will post a full review of the book when I finish reading it.)
What is var?
The var keyword is used in variable declarations instead of a type. The technical term for var is “implicitly typed local variable declaration.” The variable itself is still statically typed (the type is determined when the code is compiled), and it is still strongly typed (the type cannot change once it has been declared). The difference is that we are no longer explicitly stating the variable’s type in our source code; instead, the compiler infers the type of the variable based upon the initialize for the variable. For example:
var customerFirstName = "Jimmy";
var stopwatch = new System.Timers.Timer();
In this example, maxValue is compiled with a type of System.Int32, customerFirstName is a System.String, and stopwatch is System.Timers.Timer. In case it is not obvious, when using var to declare a variable, an initializer in the declaration is mandatory. In addition, the initializer has a few restrictions on it, which include the following:
It must be an expression that returns a value with a type; anonymous function declarations, for example (such as lambdas) are not valid, but literal expressions and object constructors are allowed.
It must not return the null type.
It must not refer to the variable being declared.
Only one declaration per statement is allowed; multiple declarations are not permitted.
For the full details, see 8.5.1 of the C# 3.0 Language Specification (DOC format).
What makes var useful?
Well, it depends on who you ask. One thing that everyone agrees on is that var is needed when declaring variables with anonymous types, such as when dealing with LINQ; using it in this scenario saves many headaches since you let the compiler worry about the type inference. Technically speaking, you can use LINQ without var, but it isn’t recommended; the overhead caused by not using it (such as trying to figure out the return type of a LINQ expression) is not worth any amount of “stylistic purity.”
One school of thought is that using var makes the code look cleaner because your declarations all line up nicely and are not cluttered with type declarations. These people also state that because you are working in C# in Visual Studio, if you really want to know the type of something, IntelliSense will let you know the type. These people also feel that using var makes it easier to change your code and makes the coding “feel” a bit more like a dynamic language such as PHP or Ruby. Another school of thought is that using var when it is not necessary is a form of laziness and that it trades a few keystrokes for decreased readability. There is a “compromise position” of thought that says that using var where the type is obvious is perfectly fine, but to not overdo it.
Where you stand in this debate is a matter of personal style. There are no technical reasons to use var at all, even with LINQ; the code is still strongly and statically typed.
I never understood the reasons to use var — its advantages were simply not obvious to me until I started doing the research for this article and found out why other developers use it. While I am not entirely convinced of its usefulness, I am willing to give it a try and see if it improves my workflow. Let me know your thoughts on var or any questions you might have on it.
J.Ja
No comments:
Post a Comment