2

Possible Duplicate:
Use of var keyword in C#
What's the point of the var keyword?

I am a bit confused here in using Implicit typing over Explicit typing.

As quoted by MSDN in C# Coding Standards:

Use implicit typing for local variables when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important.

My question is, when we already know the underlying variable type, why do we need to use implicit typing here?

What would be the advantage?

Kindly help to clarify my doubt.

Community
  • 1
  • 1
Jayanti Bose
  • 57
  • 1
  • 6
  • The advantage is also saving keystrokes, when your method return type is very complex and/or generic (for example `MyVeryComplexGenericType>>`;), you save some space just by using `var`. – Karel Frajták Oct 09 '12 at 07:10
  • 3
    It has been discussed so many times on SO,[here](http://stackoverflow.com/questions/236878/what-to-use-var-or-object-name-type), [here](http://stackoverflow.com/questions/41479/use-of-var-keyword-in-c-sharp), [here](http://stackoverflow.com/questions/1205329/c-sharp-var-keyword-usage),[here](http://stackoverflow.com/questions/884555/advantage-of-var-keyword-in-c-sharp-3-0) – Habib Oct 09 '12 at 07:10
  • Also note that you don't always know the type (if it's an anonymous one for example). – George Duckett Oct 09 '12 at 07:30

6 Answers6

5

take this as an example:

var q = from c in myCollection
        select new
    { c.Value1, c.Value2 };

we can't determine the datatype of q here because it's generated at run time "anonymus-type"
and that is the main purpose of it

Alaa Jabre
  • 1,843
  • 5
  • 26
  • 52
3

when we already know the underlying variable type, why do we need to use implicit typing here? What would be the advantage?

It's just for coding convinience, fast typing, if you wish, plus your line becomes shorter.

At the end, the type is visible on the right side of assignment, in that case.

Tigran
  • 61,654
  • 8
  • 86
  • 123
3

Just look at this:

Collection<KeyValuePair<Predicate<T>, Action<T>>> x = 
new Collection<KeyValuePair<Predicate<T>, Action<T>>>();

And now look at this:

var x = new Collection<KeyValuePair<Predicate<T>, Action<T>>>();

And, I dare, I double dare you, to tell me that there is no adventage in using the var keyword.

Note: this is based on an actual declaration in some project I rather not mention.

Chances are that you think there is some drawback in using the var keyword, well, there are, but they are all at compilation time. Your executable is as good as always. That's right var isn't the same as object, dynamic, variant, not at all! Instead it tells the compiler to declare the variable with the type of whatever you are assigning to it.

For example:

var x = 1;
x  = "something"; //Error!!!

Ok, that may sound silly. "I know the type" - you say - "Why can't I just put it down?" - you ask - "Look, it is easy:"

int x = 1;

Well, three reasons:

  • Sometimes you don't know the type, as Star mentions.
  • Sometimes you just don't want to type the type (hint: look at the begining of this answer).
  • Sometimes you want to have the flexibility to not need to tell the type.

This last point in particular comes in handy when creating Text Transformation Templates or Code Snippets, but also in you day to day copy paste.

Yet, just consider if you changed the return type of some arcane method... say you had:

List<string> MamboJambo()
{
    //...
}

And now you have changed it to:

IList<string> MamboJambo()
{
    //...
}

Oh, no! You have to update 50 classes now. Wait what? No, you don't! Because you have been following that recommendation that says to always use var.

Note: Ok, not realistic example, still it gets the point across.

Community
  • 1
  • 1
Theraot
  • 31,890
  • 5
  • 57
  • 86
1

When you know the underlying type, the only advantage you get from implicitly typed variables is not having to redefine them if you ever change the original type (for a compatible one).

Basically, the best advantage in implicitly typed variable is assigning types which tend to be long and ever-changing (like linq enumerables or queryables)

Jcl
  • 27,696
  • 5
  • 61
  • 92
0

It declares an implicitly typed variable. That is, at compile time it wil determine the type on its own so you don't have to type it. Its main purpose is to declare a variable to wich you want to asign an anonymus method for example. Basically it allows you to type less, nothing more, also from a code readers point of view its much better to specify the exact type when possible.

Freeman
  • 5,691
  • 3
  • 29
  • 41
0

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 maxValue = 500;    
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 more: http://www.techrepublic.com/blog/programming-and-development/code-concepts-cs-var-keyword/1461

  • I'm aware that you only tried to explain the use of `var` and did not recommend it, but in my opinion these are good examples **not** to use `var`. In the first case with 500, it could also be a `uint` or a `short` or even a `ushort`, most developers are not sure which one. In the last case with the variable stopwatch, i would expect a variable of type `System.Diagnostics.Stopwatch` not a timer, so a hint at the begin of the line would certainly be helpful. – martinstoeckli Oct 09 '12 at 08:05