Redundancy in C#? - c#

Take the following snippet:
List<int> distances = new List<int>();
Was the redundancy intended by the language designers? If so, why?

The reason the code appears to be redundant is because, to a novice programmer, it appears to be defining the same thing twice. But this is not what the code is doing. It is defining two separate things that just happen to be of the same type. It is defining the following:
A variable named distances of type List<int>.
An object on the heap of type List<int>.
Consider the following:
Person[] coworkers = new Employee[20];
Here the non-redundancy is clearer, because the variable and the allocated object are of two different types (a situation that is legal if the object’s type derives from or implements the variable’s type).

What's redudant about this?
List<int> listOfInts = new List<int>():
Translated to English: (EDIT, cleaned up a little for clarification)
Create a pointer of type List<int> and name it listofInts.
listOfInts is now created but its just a reference pointer pointing to nowhere (null)
Now, create an object of type List<int> on the heap, and return the pointer to listOfInts.
Now listOfInts points to a List<int> on the heap.
Not really verbose when you think about what it does.
Of course there is an alternative:
var listOfInts = new List<int>();
Here we are using C#'s type inference, because you are assigning to it immediately, C# can figure out what type you want to create by the object just created in the heap.
To fully understand how the CLR handles types, I recommend reading CLR Via C#.

You could always say:
var distances = new List<int>();

As others have said: var removes the redundancy, but it has potential negative maintenance consequences. I'd say it also has potential positive maintenance consequences.
Fortunately Eric Lippert writes about it a lot more eloquently than I do:
http://csharpindepth.com/ViewNote.aspx?NoteID=63
http://csharpindepth.com/ViewNote.aspx?NoteID=61

Because declaring a type doesn't necessarily have anything to do with initializing it.
I can declare
List<int> foo;
and leave it to be initialized later. Where's the redundancy then? Maybe it receives the value from another function like BuildList().
As others have mentioned the new var keyword lets you get around that, but you have to initialize the variable at declaration so that the compiler can tell what type it is.

instead of thinking of it as redundant, think of that construct as a feature to allow you to save a line.
instead of having
List distances;
distances = new List();
c# lets you put them on one line.
One line says "I will be using a variable called distances, and it will be of type List." Another line says "Allocate a new List and call the parameterless constructor".
Is that too redundant? Perhaps. doing it this way gives you some things, though
1. Separates out the variable declaration from object allocation. Allowing:
IEnumerable<int> distances = new List<int>();
// or more likely...
IEnumerable<int> distances = GetList();
2. It allows for more strong static type checking by the compiler - giving compiler errors when your declarations don't match the assignments, rather than runtime errors.
Are both of these required for writing software? No. There are plenty of languages that don't do this, and/or differ on many other points.
"Doctor! it hurts when I do this!" - "Don't do that anymore"
If you find that you don't need or want the things that c# gives you, try other languages. Even if you don't use them, knowing other ones can give you a huge boost in how you approach problems. If you do use one, great!
Either way, you may find enough perspective to allow yourself to say "I don't need the strict static type checking enforced by the c# compiler. I'll use python", rather than flaming c# as too redundant.

Could also do:
var distances = new List<int>();

The compiler improvements for C# 3.0 (which corresponds with .Net 3.5) eliminate some of this sort of thing. So your code can now be written as:
var distances = new List<int>();
The updated compiler is much better at figuring out types based on additional information in the statement. That means that there are fewer instances where you need to specify a type either for an assignment, or as part of a Generic.
That being said, there are still some areas which could be improved. Some of that is API and some is simply due to the restrictions of strong typing.

The redunancy wasn't intended, per se, but was a side-effect of the fact that all variables and fields needed to have a type declaration. When you take into account that all object instantiations also mention the type's name in a new expression, you get redundant looking statements.
Now with type-inferencing using the var keyword, that redundancy can be eliminated. The compiler is smart enough to figure it out. The next C++ also has an auto keyword that does the same thing.
The main reason they introduced var, though, was for anonymous types, which have no name:
var x = new {Foo = Bar, Number = 1};

It's only "redundant" if you are comparing it to dynamically typed languages. It's useful for polymorphism and finding bugs at compile time. Also, it makes code auto-complete/intellisense easier for your IDE (if you use one).

A historical artifact of static typing / C syntax; compare the Ruby example:
distances = []

C# is definitely getting less verbose after the addition of functional support.

Use var if it is obvious what the type is to the reader.
//Use var here
var names = new List<string>();
//but not here
List<string> names = GetNames();
From microsofts C# programing guide
The var keyword can also be useful
when the specific type of the variable
is tedious to type on the keyboard, or
is obvious, or does not add to the
readability of the code

Your particular example is indeed a bit verbose but in most ways C# is rather lean.
I'd much prefer this (C#)
int i;
to this (VB.NET)
Dim i as Integer
Now, the particular example you chose is something about .NET in general which is a bit on the long side, but I don't think that's C#'s fault. Maybe the question should be rephrased "Why is .NET code so verbose?"

I see one other problem with the using of var for laziness like that
var names = new List<string>();
If you use var, the variable named "names" is typed as List<string>, but you would eventually only use one of the interfaces inherited by List<T>.
IList<string> = new List<string>();
ICollection<string> = new List<string>();
IEnumerable<string> = new List<string>();
You can automatically use everything of that, but can you consider what interface you wanted to use at the time you wrote the code?
The var keyword does not improve readability in this example.

In many of the answers to this question, the authors are thinking like compilers or apologists. An important rule of good programming is Don't repeat yourself!
Avoiding this unnecessary repetition is an explicit design goal of Go, for example:
Stuttering (foo.Foo* myFoo = new(foo.Foo)) is reduced by simple type derivation using the := declare-and-initialize construct.

Because we're addicted to compilers and compiler errors.

Related

C# Making a new instance of a class with or without "var" [duplicate]

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?
For example I rather lazily used var in questionable circumstances, e.g.:-
foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.
More legitimate uses of var are as follows:-
var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.
Interestingly LINQ seems to be a bit of a grey area, e.g.:-
var results = from r in dataContext.SomeTable
select r; // Not *entirely clear* what results will be here.
It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.
It's even worse when it comes to LINQ to objects, e.g.:-
var results = from item in someList
where item != 3
select item;
This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.
There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type.
var does maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
I still think 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> or BindingList<Order> - all I want is to keep that list in memory to iterate over it or get its count or something later on.
Contrast the above declaration with:
ObservableCollection<Order> orders = cust.Orders;
To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection<Order> to IList<Order>) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.
I use var extensively. There has been criticism that this diminishes the readability of the code, but no argument to support that claim.
Admittedly, it may mean that it's not clear what type we are dealing with. So what? This is actually the point of a decoupled design. When dealing with interfaces, you are emphatically not interested in the type a variable has. var takes this much further, true, but I think that the argument remains the same from a readability point of view: The programmer shouldn't actually be interested in the type of the variable but rather in what a variable does. This is why Microsoft also calls type inference “duck typing.”
So, what does a variable do when I declare it using var? Easy, it does whatever IntelliSense tells me it does. Any reasoning about C# that ignores the IDE falls short of reality. In practice, every C# code is programmed in an IDE that supports IntelliSense.
If I am using a var declared variable and get confused what the variable is there for, there's something fundamentally wrong with my code. var is not the cause, it only makes the symptoms visible. Don't blame the messenger.
Now, the C# team has released a coding guideline stating that var should only be used to capture the result of a LINQ statement that creates an anonymous type (because here, we have no real alternative to var). Well, screw that. As long as the C# team doesn't give me a sound argument for this guideline, I am going to ignore it because in my professional and personal opinion, it's pure baloney. (Sorry; I've got no link to the guideline in question.)
Actually, there are some (superficially) good explanations on why you shouldn't use var but I still believe they are largely wrong. Take the example of “searchabililty”: the author claims that var makes it hard to search for places where MyType is used. Right. So do interfaces. Actually, why would I want to know where the class is used? I might be more interested in where it is instantiated and this will still be searchable because somewhere its constructor has to be invoked (even if this is done indirectly, the type name has to be mentioned somewhere).
Var, in my opinion, in C# is a good thingtm. Any variable so typed is still strongly typed, but it gets its type from the right-hand side of the assignment where it is defined. Because the type information is available on the right-hand side, in most cases, it's unnecessary and overly verbose to also have to enter it on the left-hand side. I think this significantly increases readability without decreasing type safety.
From my perspective, using good naming conventions for variables and methods is more important from a readability perspective than explicit type information. If I need the type information, I can always hover over the variable (in VS) and get it. Generally, though, explicit type information shouldn't be necessary to the reader. For the developer, in VS you still get Intellisense, regardless of how the variable is declared. Having said all of that, there may still be cases where it does make sense to explicitly declare the type -- perhaps you have a method that returns a List<T>, but you want to treat it as an IEnumerable<T> in your method. To ensure that you are using the interface, declaring the variable of the interface type can make this explicit. Or, perhaps, you want to declare a variable without an initial value -- because it immediately gets a value based on some condition. In that case you need the type. If the type information is useful or necessary, go ahead and use it. I feel, though, that typically it isn't necessary and the code is easier to read without it in most cases.
Neither of those is absolutely true; var can have both positive and negative effects on readability. In my opinion, var should be used when either of the following is true:
The type is anonymous (well, you don't have any choice here, as it must be var in this case)
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.
From Eric Lippert, a Senior Software Design Engineer on the C# team:
Why was the var keyword introduced?
There are two reasons, one which
exists today, one which will crop up
in 3.0.
The first reason is that this code is
incredibly ugly because of all the
redundancy:
Dictionary<string, List<int>> mylists = new Dictionary<string, List<int>>();
And that's a simple example – I've
written worse. Any time you're forced
to type exactly the same thing twice,
that's a redundancy that we can
remove. Much nicer to write
var mylists = new Dictionary<string,List<int>>();
and let the compiler figure out what
the type is based on the assignment.
Second, C# 3.0 introduces anonymous
types. Since anonymous types by
definition have no names, you need to
be able to infer the type of the
variable from the initializing
expression if its type is anonymous.
Emphasis mine. The whole article, C# 3.0 is still statically typed, honest!, and the ensuing series are pretty good.
This is what var is for. Other uses probably will not work so well. Any comparison to JScript, VBScript, or dynamic typing is total bunk. Note again, var is required in order to have certain other features work in .NET.
I think the use of var should be coupled with wisely-chosen variable names.
I have no problem using var in a foreach statement, provided it's not like this:
foreach (var c in list) { ... }
If it were more like this:
foreach (var customer in list) { ... }
... then someone reading the code would be much more likely to understand what "list" is. If you have control over the name of the list variable itself, that's even better.
The same can apply to other situations. This is pretty useless:
var x = SaveFoo(foo);
... but this makes sense:
var saveSucceeded = SaveFoo(foo);
Each to his own, I guess. I've found myself doing this, which is just insane:
var f = (float)3;
I need some sort of 12-step var program. My name is Matt, and I (ab)use var.
We've adopted the ethos "Code for people, not machines", based on the assumption that you spend multiple times longer in maintenance mode than on new development.
For me, that rules out the argument that the compiler "knows" what type the variable is - sure, you can't write invalid code the first time because the compiler stops your code from compiling, but when the next developer is reading the code in 6 months time they need to be able to deduce what the variable is doing correctly or incorrectly and quickly identify the cause of issues.
Thus,
var something = SomeMethod();
is outlawed by our coding standards, but the following is encouraged in our team because it increases readability:
var list = new List<KeyValuePair<string, double>>();
FillList( list );
foreach( var item in list ) {
DoWork( item );
}
It's not bad, it's more a stylistic thing, which tends to be subjective. It can add inconsistencies, when you do use var and when you don't.
Another case of concern, in the following call you can't tell just by looking at the code the type returned by CallMe:
var variable = CallMe();
That's my main complain against var.
I use var when I declare anonymous delegates in methods, somehow var looks cleaner than if I'd use Func. Consider this code:
var callback = new Func<IntPtr, bool>(delegate(IntPtr hWnd) {
...
});
EDIT: Updated the last code sample based on Julian's input
Var is not like variant at all. The variable is still strongly typed, it's just that you don't press keys to get it that way. You can hover over it in Visual Studio to see the type. If you're reading printed code, it's possible you might have to think a little to work out what the type is. But there is only one line that declares it and many lines that use it, so giving things decent names is still the best way to make your code easier to follow.
Is using Intellisense lazy? It's less typing than the whole name. Or are there things that are less work but don't deserve criticism? I think there are, and var is one of them.
The most likely time you'll need this is for anonymous types (where it is 100% required); but it also avoids repetition for the trivial cases, and IMO makes the line clearer. I don't need to see the type twice for a simple initialization.
For example:
Dictionary<string, List<SomeComplexType<int>>> data = new Dictionary<string, List<SomeComplexType<int>>>();
(please don't edit the hscroll in the above - it kinda proves the point!!!)
vs:
var data = new Dictionary<string, List<SomeComplexType<int>>>();
There are, however, occasions when this is misleading, and can potentially cause bugs. Be careful using var if the original variable and initialized type weren't identical. For example:
static void DoSomething(IFoo foo) {Console.WriteLine("working happily") }
static void DoSomething(Foo foo) {Console.WriteLine("formatting hard disk...");}
// this working code...
IFoo oldCode = new Foo();
DoSomething(oldCode);
// ...is **very** different to this code
var newCode = new Foo();
DoSomething(newCode);
One specific case where var is difficult: offline code reviews, especially the ones done on paper.
You can't rely on mouse-overs for that.
I don't see what the big deal is..
var something = someMethod(); // Type of 'something' not clear <-- not to the compiler!
You still have full intellisense on 'something', and for any ambiguous case you have your unit tests, right? ( do you? )
It's not varchar, it's not dim, and it's certainly not dynamic or weak typing. It is stopping maddnes like this:
List<somethinglongtypename> v = new List<somethinglongtypename>();
and reducing that total mindclutter to:
var v = new List<somethinglongtypename>();
Nice, not quite as nice as:
v = List<somethinglongtypename>();
But then that's what Boo is for.
If someone is using the var keyword because they don't want to "figure out the type", that is definitely the wrong reason. The var keyword doesn't create a variable with a dynamic type, the compiler still has to know the type. As the variable always has a specific type, the type should also be evident in the code if possible.
Good reasons to use the var keyword are for example:
Where it's needed, i.e. to declare a reference for an anonymous type.
Where it makes the code more readable, i.e. removing repetetive declarations.
Writing out the data type often makes the code easier to follow. It shows what data types you are using, so that you don't have to figure out the data type by first figuring out what the code does.
Given how powerful Intellisense is now, I am not sure var is any harder to read than having member variables in a class, or local variables in a method which are defined off the visible screen area.
If you have a line of code such as
IDictionary<BigClassName, SomeOtherBigClassName> nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();
Is is much easier or harder to read than:
var nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();
I think the key thing with VAR is to only use it where appropriate i.e. when doing things in Linq that it facilitates (and probably in other cases).
If you've got a type for something in the then you should use it - not to do so is simple laziness (as opposed to creative laziness which is generally to be encouraged - good programmers oft work very hard to be lazy and could be considered the source of the thing in the first place).
A blanket ban is as bad as abusing the construct in the first place but there does need to be a sensible coding standard.
The other thing to remember is that its not a VB type var in that it can't change types - it is a strongly typed variable its just that the type is inferred (which is why there are people that will argue that its not unreasonable to use it in, say, a foreach but I'd disagree for reasons of both readability and maintainability).
I suspect this one is going to run and run (-:
Murph
Sure, int is easy, but when the variable's type is IEnumerable<MyStupidLongNamedGenericClass<int, string>>, var makes things much easier.
Stolen from the post on this issue at CodingHorror:
Unfortunately, you and everyone else pretty much got it wrong. While I agree with you that redundancy is not a good thing, the better way to solve this issue would have been to do something like the following:
MyObject m = new();
Or if you are passing parameters:
Person p = new("FirstName", "LastName);
Where in the creation of a new object, the compiler infers the type from the left-hand side, and not the right. This has other advantages over "var", in that it could be used in field declarations as well (there are also some other areas that it could be useful as well, but I won't get into it here).
In the end, it just wasn't intended to reduce redundancy. Don't get me wrong, "var" is VERY important in C# for anonymous types/projections, but the use here is just WAY off (and I've been saying this for a long, long time) as you obfuscate the type that is being used. Having to type it twice is too often, but declaring it zero times is too few.
Nicholas Paldino .NET/C# MVP on June 20, 2008 08:00 AM
I guess if your main concern is to have to type less -- then there isn't any argument that's going to sway you from using it.
If you are only going to ever be the person who looks at your code, then who cares? Otherwise, in a case like this:
var people = Managers.People
it's fine, but in a case like this:
var fc = Factory.Run();
it short circuits any immediate type deductions my brain could begin forming from the 'English' of the code.
Otherwise, just use your best judgment and programming 'courtesy' towards others who might have to work on your project.
Using var instead of explicit type makes refactorings much easier (therefore I must contradict the previous posters who meant it made no difference or it was purely "syntactic sugar").
You can change the return type of your methods without changing every file where this method is called. Imagine
...
List<MyClass> SomeMethod() { ... }
...
which is used like
...
IList<MyClass> list = obj.SomeMethod();
foreach (MyClass c in list)
System.Console.WriteLine(c.ToString());
...
If you wanted to refactor SomeMethod() to return an IEnumerable<MySecondClass>, you would have to change the variable declaration (also inside the foreach) in every place you used the method.
If you write
...
var list = obj.SomeMethod();
foreach (var element in list)
System.Console.WriteLine(element.ToString());
...
instead, you don't have to change it.
#aku: One example is code reviews. Another example is refactoring scenarios.
Basically I don't want to go type-hunting with my mouse. It might not be available.
It's a matter of taste. All this fussing about the type of a variable disappears when you get used to dynamically typed languages. That is, if you ever start to like them (I'm not sure if everybody can, but I do).
C#'s var is pretty cool in that it looks like dynamic typing, but actually is static typing - the compiler enforces correct usage.
The type of your variable is not really that important (this has been said before). It should be relatively clear from the context (its interactions with other variables and methods) and its name - don't expect customerList to contain an int...
I am still waiting to see what my boss thinks of this matter - I got a blanket "go ahead" to use any new constructs in 3.5, but what will we do about maintenance?
In your comparison between IEnumerable<int> and IEnumerable<double> you don't need to worry - if you pass the wrong type your code won't compile anyway.
There's no concern about type-safety, as var is not dynamic. It's just compiler magic and any type unsafe calls you make will get caught.
Var is absolutely needed for Linq:
var anonEnumeration =
from post in AllPosts()
where post.Date > oldDate
let author = GetAuthor( post.AuthorId )
select new {
PostName = post.Name,
post.Date,
AuthorName = author.Name
};
Now look at anonEnumeration in intellisense and it will appear something like IEnumerable<'a>
foreach( var item in anonEnumeration )
{
//VS knows the type
item.PostName; //you'll get intellisense here
//you still have type safety
item.ItemId; //will throw a compiler exception
}
The C# compiler is pretty clever - anon types generated separately will have the same generated type if their properties match.
Outside of that, as long as you have intellisense it makes good sense to use var anywhere the context is clear.
//less typing, this is good
var myList = new List<UnreasonablyLongClassName>();
//also good - I can't be mistaken on type
var anotherList = GetAllOfSomeItem();
//but not here - probably best to leave single value types declared
var decimalNum = 123.456m;
I guess it depends on your perspective. I personally have never had any difficulty understanding a piece of code because of var "misuse", and my coworkers and I use it quite a lot all over. (I agree that Intellisense is a huge aid in this regard.) I welcome it as a way to remove repetitive cruft.
After all, if statements like
var index = 5; // this is supposed to be bad
var firstEligibleObject = FetchSomething(); // oh no what type is it
// i am going to die if i don't know
were really that impossible to deal with, nobody would use dynamically typed languages.
I only use var when it's clear to see what type is used.
For example, I would use var in this case, because you can see immediately that x will be of the type "MyClass":
var x = new MyClass();
I would NOT use var in cases like this, because you have to drag the mouse over the code and look at the tooltip to see what type MyFunction returns:
var x = MyClass.MyFunction();
Especially, I never use var in cases where the right side is not even a method, but only a value:
var x = 5;
(because the compiler can't know if I want a byte, short, int or whatever)
To me, the antipathy towards var illustrates why bilingualism in .NET is important. To those C# programmers who have also done VB .NET, the advantages of var are intuitively obvious. The standard C# declaration of:
List<string> whatever = new List<string>();
is the equivalent, in VB .NET, of typing this:
Dim whatever As List(Of String) = New List(Of String)
Nobody does that in VB .NET, though. It would be silly to, because since the first version of .NET you've been able to do this...
Dim whatever As New List(Of String)
...which creates the variable and initializes it all in one reasonably compact line. Ah, but what if you want an IList<string>, not a List<string>? Well, in VB .NET that means you have to do this:
Dim whatever As IList(Of String) = New List(Of String)
Just like you'd have to do in C#, and obviously couldn't use var for:
IList<string> whatever = new List<string>();
If you need the type to be something different, it can be. But one of the basic principles of good programming is reducing redundancy, and that's exactly what var does.
Use it for anonymous types - that's what it's there for. Anything else is a use too far. Like many people who grew up on C, I'm used to looking at the left of the declaration for the type. I don't look at the right side unless I have to. Using var for any old declaration makes me do that all the time, which I personally find uncomfortable.
Those saying 'it doesn't matter, use what you're happy with' are not seeing the whole picture. Everyone will pick up other people's code at one point or another and have to deal with whatever decisions they made at the time they wrote it. It's bad enough having to deal with radically different naming conventions, or - the classic gripe - bracing styles, without adding the whole 'var or not' thing into the mix. The worst case will be where one programmer didn't use var and then along comes a maintainer who loves it, and extends the code using it. So now you have an unholy mess.
Standards are a good thing precisely because they mean you're that much more likely to be able to pick up random code and be able to grok it quickly. The more things that are different, the harder that gets. And moving to the 'var everywhere' style makes a big difference.
I don't mind dynamic typing, and I don't mind implict typing - in languages that are designed for them. I quite like Python. But C# was designed as a statically explicitly-typed language and that's how it should stay. Breaking the rules for anonymous types was bad enough; letting people take that still further and break the idioms of the language even more is something I'm not happy with. Now that the genie is out of the bottle, it'll never go back in. C# will become balkanised into camps. Not good.
Many time during testing, I find myself having code like this:
var something = myObject.SomeProperty.SomeOtherThing.CallMethod();
Console.WriteLine(something);
Now, sometimes, I'll want to see what the SomeOtherThing itself contains, SomeOtherThing is not the same type that CallMethod() returns. Since I'm using var though, I just change this:
var something = myObject.SomeProperty.SomeOtherThing.CallMethod();
to this:
var something = myObject.SomeProperty.SomeOtherThing;
Without var, I'd have to keep changing the declared type on the left hand side as well. I know it's minor, but it's extremely convenient.
For the afficionados that think var saves time, it takes less keystrokes to type:
StringBuilder sb = new StringBuilder();
than
var sb = new StringBuilder();
Count em if you don't believe me...
19 versus 21
I'll explain if I have to, but just try it... (depending on the current state of your intellisense you may have to type a couple more for each one)
And it's true for every type you can think of!!
My personal feeling is that var should never be used except where the type is not known because it reduces recognition readabiltiy in code. It takes the brain longer to recognize the type than a full line. Old timers who understand machine code and bits know exactly what I am talking about. The brain processes in parallel and when you use var you force it to serialize its input. Why would anyone want to make their brain work harder? That's what computers are for.
I split var all over the places, the only questionable places for me are internal short types, e.g. I prefer int i = 3; over var i = 3;
It can certainly make things simpler, from code I wrote yesterday:
var content = new Queue<Pair<Regex, Func<string, bool>>>();
...
foreach (var entry in content) { ... }
This would have be extremely verbose without var.
Addendum: A little time spent with a language with real type inference (e.g. F#) will show just how good compilers are at getting the type of expressions right. It certainly has meant I tend to use var as much as I can, and using an explicit type now indicates that the variable is not of the initialising expression's type.
None, except that you don't have to write the type name twice. http://msdn.microsoft.com/en-us/library/bb383973.aspx

declare type vs use var [duplicate]

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?
For example I rather lazily used var in questionable circumstances, e.g.:-
foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.
More legitimate uses of var are as follows:-
var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.
Interestingly LINQ seems to be a bit of a grey area, e.g.:-
var results = from r in dataContext.SomeTable
select r; // Not *entirely clear* what results will be here.
It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.
It's even worse when it comes to LINQ to objects, e.g.:-
var results = from item in someList
where item != 3
select item;
This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.
There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type.
var does maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
I still think 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> or BindingList<Order> - all I want is to keep that list in memory to iterate over it or get its count or something later on.
Contrast the above declaration with:
ObservableCollection<Order> orders = cust.Orders;
To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection<Order> to IList<Order>) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.
I use var extensively. There has been criticism that this diminishes the readability of the code, but no argument to support that claim.
Admittedly, it may mean that it's not clear what type we are dealing with. So what? This is actually the point of a decoupled design. When dealing with interfaces, you are emphatically not interested in the type a variable has. var takes this much further, true, but I think that the argument remains the same from a readability point of view: The programmer shouldn't actually be interested in the type of the variable but rather in what a variable does. This is why Microsoft also calls type inference “duck typing.”
So, what does a variable do when I declare it using var? Easy, it does whatever IntelliSense tells me it does. Any reasoning about C# that ignores the IDE falls short of reality. In practice, every C# code is programmed in an IDE that supports IntelliSense.
If I am using a var declared variable and get confused what the variable is there for, there's something fundamentally wrong with my code. var is not the cause, it only makes the symptoms visible. Don't blame the messenger.
Now, the C# team has released a coding guideline stating that var should only be used to capture the result of a LINQ statement that creates an anonymous type (because here, we have no real alternative to var). Well, screw that. As long as the C# team doesn't give me a sound argument for this guideline, I am going to ignore it because in my professional and personal opinion, it's pure baloney. (Sorry; I've got no link to the guideline in question.)
Actually, there are some (superficially) good explanations on why you shouldn't use var but I still believe they are largely wrong. Take the example of “searchabililty”: the author claims that var makes it hard to search for places where MyType is used. Right. So do interfaces. Actually, why would I want to know where the class is used? I might be more interested in where it is instantiated and this will still be searchable because somewhere its constructor has to be invoked (even if this is done indirectly, the type name has to be mentioned somewhere).
Var, in my opinion, in C# is a good thingtm. Any variable so typed is still strongly typed, but it gets its type from the right-hand side of the assignment where it is defined. Because the type information is available on the right-hand side, in most cases, it's unnecessary and overly verbose to also have to enter it on the left-hand side. I think this significantly increases readability without decreasing type safety.
From my perspective, using good naming conventions for variables and methods is more important from a readability perspective than explicit type information. If I need the type information, I can always hover over the variable (in VS) and get it. Generally, though, explicit type information shouldn't be necessary to the reader. For the developer, in VS you still get Intellisense, regardless of how the variable is declared. Having said all of that, there may still be cases where it does make sense to explicitly declare the type -- perhaps you have a method that returns a List<T>, but you want to treat it as an IEnumerable<T> in your method. To ensure that you are using the interface, declaring the variable of the interface type can make this explicit. Or, perhaps, you want to declare a variable without an initial value -- because it immediately gets a value based on some condition. In that case you need the type. If the type information is useful or necessary, go ahead and use it. I feel, though, that typically it isn't necessary and the code is easier to read without it in most cases.
Neither of those is absolutely true; var can have both positive and negative effects on readability. In my opinion, var should be used when either of the following is true:
The type is anonymous (well, you don't have any choice here, as it must be var in this case)
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.
From Eric Lippert, a Senior Software Design Engineer on the C# team:
Why was the var keyword introduced?
There are two reasons, one which
exists today, one which will crop up
in 3.0.
The first reason is that this code is
incredibly ugly because of all the
redundancy:
Dictionary<string, List<int>> mylists = new Dictionary<string, List<int>>();
And that's a simple example – I've
written worse. Any time you're forced
to type exactly the same thing twice,
that's a redundancy that we can
remove. Much nicer to write
var mylists = new Dictionary<string,List<int>>();
and let the compiler figure out what
the type is based on the assignment.
Second, C# 3.0 introduces anonymous
types. Since anonymous types by
definition have no names, you need to
be able to infer the type of the
variable from the initializing
expression if its type is anonymous.
Emphasis mine. The whole article, C# 3.0 is still statically typed, honest!, and the ensuing series are pretty good.
This is what var is for. Other uses probably will not work so well. Any comparison to JScript, VBScript, or dynamic typing is total bunk. Note again, var is required in order to have certain other features work in .NET.
I think the use of var should be coupled with wisely-chosen variable names.
I have no problem using var in a foreach statement, provided it's not like this:
foreach (var c in list) { ... }
If it were more like this:
foreach (var customer in list) { ... }
... then someone reading the code would be much more likely to understand what "list" is. If you have control over the name of the list variable itself, that's even better.
The same can apply to other situations. This is pretty useless:
var x = SaveFoo(foo);
... but this makes sense:
var saveSucceeded = SaveFoo(foo);
Each to his own, I guess. I've found myself doing this, which is just insane:
var f = (float)3;
I need some sort of 12-step var program. My name is Matt, and I (ab)use var.
We've adopted the ethos "Code for people, not machines", based on the assumption that you spend multiple times longer in maintenance mode than on new development.
For me, that rules out the argument that the compiler "knows" what type the variable is - sure, you can't write invalid code the first time because the compiler stops your code from compiling, but when the next developer is reading the code in 6 months time they need to be able to deduce what the variable is doing correctly or incorrectly and quickly identify the cause of issues.
Thus,
var something = SomeMethod();
is outlawed by our coding standards, but the following is encouraged in our team because it increases readability:
var list = new List<KeyValuePair<string, double>>();
FillList( list );
foreach( var item in list ) {
DoWork( item );
}
It's not bad, it's more a stylistic thing, which tends to be subjective. It can add inconsistencies, when you do use var and when you don't.
Another case of concern, in the following call you can't tell just by looking at the code the type returned by CallMe:
var variable = CallMe();
That's my main complain against var.
I use var when I declare anonymous delegates in methods, somehow var looks cleaner than if I'd use Func. Consider this code:
var callback = new Func<IntPtr, bool>(delegate(IntPtr hWnd) {
...
});
EDIT: Updated the last code sample based on Julian's input
Var is not like variant at all. The variable is still strongly typed, it's just that you don't press keys to get it that way. You can hover over it in Visual Studio to see the type. If you're reading printed code, it's possible you might have to think a little to work out what the type is. But there is only one line that declares it and many lines that use it, so giving things decent names is still the best way to make your code easier to follow.
Is using Intellisense lazy? It's less typing than the whole name. Or are there things that are less work but don't deserve criticism? I think there are, and var is one of them.
The most likely time you'll need this is for anonymous types (where it is 100% required); but it also avoids repetition for the trivial cases, and IMO makes the line clearer. I don't need to see the type twice for a simple initialization.
For example:
Dictionary<string, List<SomeComplexType<int>>> data = new Dictionary<string, List<SomeComplexType<int>>>();
(please don't edit the hscroll in the above - it kinda proves the point!!!)
vs:
var data = new Dictionary<string, List<SomeComplexType<int>>>();
There are, however, occasions when this is misleading, and can potentially cause bugs. Be careful using var if the original variable and initialized type weren't identical. For example:
static void DoSomething(IFoo foo) {Console.WriteLine("working happily") }
static void DoSomething(Foo foo) {Console.WriteLine("formatting hard disk...");}
// this working code...
IFoo oldCode = new Foo();
DoSomething(oldCode);
// ...is **very** different to this code
var newCode = new Foo();
DoSomething(newCode);
One specific case where var is difficult: offline code reviews, especially the ones done on paper.
You can't rely on mouse-overs for that.
I don't see what the big deal is..
var something = someMethod(); // Type of 'something' not clear <-- not to the compiler!
You still have full intellisense on 'something', and for any ambiguous case you have your unit tests, right? ( do you? )
It's not varchar, it's not dim, and it's certainly not dynamic or weak typing. It is stopping maddnes like this:
List<somethinglongtypename> v = new List<somethinglongtypename>();
and reducing that total mindclutter to:
var v = new List<somethinglongtypename>();
Nice, not quite as nice as:
v = List<somethinglongtypename>();
But then that's what Boo is for.
If someone is using the var keyword because they don't want to "figure out the type", that is definitely the wrong reason. The var keyword doesn't create a variable with a dynamic type, the compiler still has to know the type. As the variable always has a specific type, the type should also be evident in the code if possible.
Good reasons to use the var keyword are for example:
Where it's needed, i.e. to declare a reference for an anonymous type.
Where it makes the code more readable, i.e. removing repetetive declarations.
Writing out the data type often makes the code easier to follow. It shows what data types you are using, so that you don't have to figure out the data type by first figuring out what the code does.
Given how powerful Intellisense is now, I am not sure var is any harder to read than having member variables in a class, or local variables in a method which are defined off the visible screen area.
If you have a line of code such as
IDictionary<BigClassName, SomeOtherBigClassName> nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();
Is is much easier or harder to read than:
var nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();
I think the key thing with VAR is to only use it where appropriate i.e. when doing things in Linq that it facilitates (and probably in other cases).
If you've got a type for something in the then you should use it - not to do so is simple laziness (as opposed to creative laziness which is generally to be encouraged - good programmers oft work very hard to be lazy and could be considered the source of the thing in the first place).
A blanket ban is as bad as abusing the construct in the first place but there does need to be a sensible coding standard.
The other thing to remember is that its not a VB type var in that it can't change types - it is a strongly typed variable its just that the type is inferred (which is why there are people that will argue that its not unreasonable to use it in, say, a foreach but I'd disagree for reasons of both readability and maintainability).
I suspect this one is going to run and run (-:
Murph
Sure, int is easy, but when the variable's type is IEnumerable<MyStupidLongNamedGenericClass<int, string>>, var makes things much easier.
Stolen from the post on this issue at CodingHorror:
Unfortunately, you and everyone else pretty much got it wrong. While I agree with you that redundancy is not a good thing, the better way to solve this issue would have been to do something like the following:
MyObject m = new();
Or if you are passing parameters:
Person p = new("FirstName", "LastName);
Where in the creation of a new object, the compiler infers the type from the left-hand side, and not the right. This has other advantages over "var", in that it could be used in field declarations as well (there are also some other areas that it could be useful as well, but I won't get into it here).
In the end, it just wasn't intended to reduce redundancy. Don't get me wrong, "var" is VERY important in C# for anonymous types/projections, but the use here is just WAY off (and I've been saying this for a long, long time) as you obfuscate the type that is being used. Having to type it twice is too often, but declaring it zero times is too few.
Nicholas Paldino .NET/C# MVP on June 20, 2008 08:00 AM
I guess if your main concern is to have to type less -- then there isn't any argument that's going to sway you from using it.
If you are only going to ever be the person who looks at your code, then who cares? Otherwise, in a case like this:
var people = Managers.People
it's fine, but in a case like this:
var fc = Factory.Run();
it short circuits any immediate type deductions my brain could begin forming from the 'English' of the code.
Otherwise, just use your best judgment and programming 'courtesy' towards others who might have to work on your project.
Using var instead of explicit type makes refactorings much easier (therefore I must contradict the previous posters who meant it made no difference or it was purely "syntactic sugar").
You can change the return type of your methods without changing every file where this method is called. Imagine
...
List<MyClass> SomeMethod() { ... }
...
which is used like
...
IList<MyClass> list = obj.SomeMethod();
foreach (MyClass c in list)
System.Console.WriteLine(c.ToString());
...
If you wanted to refactor SomeMethod() to return an IEnumerable<MySecondClass>, you would have to change the variable declaration (also inside the foreach) in every place you used the method.
If you write
...
var list = obj.SomeMethod();
foreach (var element in list)
System.Console.WriteLine(element.ToString());
...
instead, you don't have to change it.
#aku: One example is code reviews. Another example is refactoring scenarios.
Basically I don't want to go type-hunting with my mouse. It might not be available.
It's a matter of taste. All this fussing about the type of a variable disappears when you get used to dynamically typed languages. That is, if you ever start to like them (I'm not sure if everybody can, but I do).
C#'s var is pretty cool in that it looks like dynamic typing, but actually is static typing - the compiler enforces correct usage.
The type of your variable is not really that important (this has been said before). It should be relatively clear from the context (its interactions with other variables and methods) and its name - don't expect customerList to contain an int...
I am still waiting to see what my boss thinks of this matter - I got a blanket "go ahead" to use any new constructs in 3.5, but what will we do about maintenance?
In your comparison between IEnumerable<int> and IEnumerable<double> you don't need to worry - if you pass the wrong type your code won't compile anyway.
There's no concern about type-safety, as var is not dynamic. It's just compiler magic and any type unsafe calls you make will get caught.
Var is absolutely needed for Linq:
var anonEnumeration =
from post in AllPosts()
where post.Date > oldDate
let author = GetAuthor( post.AuthorId )
select new {
PostName = post.Name,
post.Date,
AuthorName = author.Name
};
Now look at anonEnumeration in intellisense and it will appear something like IEnumerable<'a>
foreach( var item in anonEnumeration )
{
//VS knows the type
item.PostName; //you'll get intellisense here
//you still have type safety
item.ItemId; //will throw a compiler exception
}
The C# compiler is pretty clever - anon types generated separately will have the same generated type if their properties match.
Outside of that, as long as you have intellisense it makes good sense to use var anywhere the context is clear.
//less typing, this is good
var myList = new List<UnreasonablyLongClassName>();
//also good - I can't be mistaken on type
var anotherList = GetAllOfSomeItem();
//but not here - probably best to leave single value types declared
var decimalNum = 123.456m;
I guess it depends on your perspective. I personally have never had any difficulty understanding a piece of code because of var "misuse", and my coworkers and I use it quite a lot all over. (I agree that Intellisense is a huge aid in this regard.) I welcome it as a way to remove repetitive cruft.
After all, if statements like
var index = 5; // this is supposed to be bad
var firstEligibleObject = FetchSomething(); // oh no what type is it
// i am going to die if i don't know
were really that impossible to deal with, nobody would use dynamically typed languages.
I only use var when it's clear to see what type is used.
For example, I would use var in this case, because you can see immediately that x will be of the type "MyClass":
var x = new MyClass();
I would NOT use var in cases like this, because you have to drag the mouse over the code and look at the tooltip to see what type MyFunction returns:
var x = MyClass.MyFunction();
Especially, I never use var in cases where the right side is not even a method, but only a value:
var x = 5;
(because the compiler can't know if I want a byte, short, int or whatever)
To me, the antipathy towards var illustrates why bilingualism in .NET is important. To those C# programmers who have also done VB .NET, the advantages of var are intuitively obvious. The standard C# declaration of:
List<string> whatever = new List<string>();
is the equivalent, in VB .NET, of typing this:
Dim whatever As List(Of String) = New List(Of String)
Nobody does that in VB .NET, though. It would be silly to, because since the first version of .NET you've been able to do this...
Dim whatever As New List(Of String)
...which creates the variable and initializes it all in one reasonably compact line. Ah, but what if you want an IList<string>, not a List<string>? Well, in VB .NET that means you have to do this:
Dim whatever As IList(Of String) = New List(Of String)
Just like you'd have to do in C#, and obviously couldn't use var for:
IList<string> whatever = new List<string>();
If you need the type to be something different, it can be. But one of the basic principles of good programming is reducing redundancy, and that's exactly what var does.
Use it for anonymous types - that's what it's there for. Anything else is a use too far. Like many people who grew up on C, I'm used to looking at the left of the declaration for the type. I don't look at the right side unless I have to. Using var for any old declaration makes me do that all the time, which I personally find uncomfortable.
Those saying 'it doesn't matter, use what you're happy with' are not seeing the whole picture. Everyone will pick up other people's code at one point or another and have to deal with whatever decisions they made at the time they wrote it. It's bad enough having to deal with radically different naming conventions, or - the classic gripe - bracing styles, without adding the whole 'var or not' thing into the mix. The worst case will be where one programmer didn't use var and then along comes a maintainer who loves it, and extends the code using it. So now you have an unholy mess.
Standards are a good thing precisely because they mean you're that much more likely to be able to pick up random code and be able to grok it quickly. The more things that are different, the harder that gets. And moving to the 'var everywhere' style makes a big difference.
I don't mind dynamic typing, and I don't mind implict typing - in languages that are designed for them. I quite like Python. But C# was designed as a statically explicitly-typed language and that's how it should stay. Breaking the rules for anonymous types was bad enough; letting people take that still further and break the idioms of the language even more is something I'm not happy with. Now that the genie is out of the bottle, it'll never go back in. C# will become balkanised into camps. Not good.
Many time during testing, I find myself having code like this:
var something = myObject.SomeProperty.SomeOtherThing.CallMethod();
Console.WriteLine(something);
Now, sometimes, I'll want to see what the SomeOtherThing itself contains, SomeOtherThing is not the same type that CallMethod() returns. Since I'm using var though, I just change this:
var something = myObject.SomeProperty.SomeOtherThing.CallMethod();
to this:
var something = myObject.SomeProperty.SomeOtherThing;
Without var, I'd have to keep changing the declared type on the left hand side as well. I know it's minor, but it's extremely convenient.
For the afficionados that think var saves time, it takes less keystrokes to type:
StringBuilder sb = new StringBuilder();
than
var sb = new StringBuilder();
Count em if you don't believe me...
19 versus 21
I'll explain if I have to, but just try it... (depending on the current state of your intellisense you may have to type a couple more for each one)
And it's true for every type you can think of!!
My personal feeling is that var should never be used except where the type is not known because it reduces recognition readabiltiy in code. It takes the brain longer to recognize the type than a full line. Old timers who understand machine code and bits know exactly what I am talking about. The brain processes in parallel and when you use var you force it to serialize its input. Why would anyone want to make their brain work harder? That's what computers are for.
I split var all over the places, the only questionable places for me are internal short types, e.g. I prefer int i = 3; over var i = 3;
It can certainly make things simpler, from code I wrote yesterday:
var content = new Queue<Pair<Regex, Func<string, bool>>>();
...
foreach (var entry in content) { ... }
This would have be extremely verbose without var.
Addendum: A little time spent with a language with real type inference (e.g. F#) will show just how good compilers are at getting the type of expressions right. It certainly has meant I tend to use var as much as I can, and using an explicit type now indicates that the variable is not of the initialising expression's type.
None, except that you don't have to write the type name twice. http://msdn.microsoft.com/en-us/library/bb383973.aspx

What should i use: var or explicitly type specify? [duplicate]

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?
For example I rather lazily used var in questionable circumstances, e.g.:-
foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.
More legitimate uses of var are as follows:-
var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.
Interestingly LINQ seems to be a bit of a grey area, e.g.:-
var results = from r in dataContext.SomeTable
select r; // Not *entirely clear* what results will be here.
It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.
It's even worse when it comes to LINQ to objects, e.g.:-
var results = from item in someList
where item != 3
select item;
This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.
There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type.
var does maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
I still think 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> or BindingList<Order> - all I want is to keep that list in memory to iterate over it or get its count or something later on.
Contrast the above declaration with:
ObservableCollection<Order> orders = cust.Orders;
To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection<Order> to IList<Order>) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.
I use var extensively. There has been criticism that this diminishes the readability of the code, but no argument to support that claim.
Admittedly, it may mean that it's not clear what type we are dealing with. So what? This is actually the point of a decoupled design. When dealing with interfaces, you are emphatically not interested in the type a variable has. var takes this much further, true, but I think that the argument remains the same from a readability point of view: The programmer shouldn't actually be interested in the type of the variable but rather in what a variable does. This is why Microsoft also calls type inference “duck typing.”
So, what does a variable do when I declare it using var? Easy, it does whatever IntelliSense tells me it does. Any reasoning about C# that ignores the IDE falls short of reality. In practice, every C# code is programmed in an IDE that supports IntelliSense.
If I am using a var declared variable and get confused what the variable is there for, there's something fundamentally wrong with my code. var is not the cause, it only makes the symptoms visible. Don't blame the messenger.
Now, the C# team has released a coding guideline stating that var should only be used to capture the result of a LINQ statement that creates an anonymous type (because here, we have no real alternative to var). Well, screw that. As long as the C# team doesn't give me a sound argument for this guideline, I am going to ignore it because in my professional and personal opinion, it's pure baloney. (Sorry; I've got no link to the guideline in question.)
Actually, there are some (superficially) good explanations on why you shouldn't use var but I still believe they are largely wrong. Take the example of “searchabililty”: the author claims that var makes it hard to search for places where MyType is used. Right. So do interfaces. Actually, why would I want to know where the class is used? I might be more interested in where it is instantiated and this will still be searchable because somewhere its constructor has to be invoked (even if this is done indirectly, the type name has to be mentioned somewhere).
Var, in my opinion, in C# is a good thingtm. Any variable so typed is still strongly typed, but it gets its type from the right-hand side of the assignment where it is defined. Because the type information is available on the right-hand side, in most cases, it's unnecessary and overly verbose to also have to enter it on the left-hand side. I think this significantly increases readability without decreasing type safety.
From my perspective, using good naming conventions for variables and methods is more important from a readability perspective than explicit type information. If I need the type information, I can always hover over the variable (in VS) and get it. Generally, though, explicit type information shouldn't be necessary to the reader. For the developer, in VS you still get Intellisense, regardless of how the variable is declared. Having said all of that, there may still be cases where it does make sense to explicitly declare the type -- perhaps you have a method that returns a List<T>, but you want to treat it as an IEnumerable<T> in your method. To ensure that you are using the interface, declaring the variable of the interface type can make this explicit. Or, perhaps, you want to declare a variable without an initial value -- because it immediately gets a value based on some condition. In that case you need the type. If the type information is useful or necessary, go ahead and use it. I feel, though, that typically it isn't necessary and the code is easier to read without it in most cases.
Neither of those is absolutely true; var can have both positive and negative effects on readability. In my opinion, var should be used when either of the following is true:
The type is anonymous (well, you don't have any choice here, as it must be var in this case)
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.
From Eric Lippert, a Senior Software Design Engineer on the C# team:
Why was the var keyword introduced?
There are two reasons, one which
exists today, one which will crop up
in 3.0.
The first reason is that this code is
incredibly ugly because of all the
redundancy:
Dictionary<string, List<int>> mylists = new Dictionary<string, List<int>>();
And that's a simple example – I've
written worse. Any time you're forced
to type exactly the same thing twice,
that's a redundancy that we can
remove. Much nicer to write
var mylists = new Dictionary<string,List<int>>();
and let the compiler figure out what
the type is based on the assignment.
Second, C# 3.0 introduces anonymous
types. Since anonymous types by
definition have no names, you need to
be able to infer the type of the
variable from the initializing
expression if its type is anonymous.
Emphasis mine. The whole article, C# 3.0 is still statically typed, honest!, and the ensuing series are pretty good.
This is what var is for. Other uses probably will not work so well. Any comparison to JScript, VBScript, or dynamic typing is total bunk. Note again, var is required in order to have certain other features work in .NET.
I think the use of var should be coupled with wisely-chosen variable names.
I have no problem using var in a foreach statement, provided it's not like this:
foreach (var c in list) { ... }
If it were more like this:
foreach (var customer in list) { ... }
... then someone reading the code would be much more likely to understand what "list" is. If you have control over the name of the list variable itself, that's even better.
The same can apply to other situations. This is pretty useless:
var x = SaveFoo(foo);
... but this makes sense:
var saveSucceeded = SaveFoo(foo);
Each to his own, I guess. I've found myself doing this, which is just insane:
var f = (float)3;
I need some sort of 12-step var program. My name is Matt, and I (ab)use var.
We've adopted the ethos "Code for people, not machines", based on the assumption that you spend multiple times longer in maintenance mode than on new development.
For me, that rules out the argument that the compiler "knows" what type the variable is - sure, you can't write invalid code the first time because the compiler stops your code from compiling, but when the next developer is reading the code in 6 months time they need to be able to deduce what the variable is doing correctly or incorrectly and quickly identify the cause of issues.
Thus,
var something = SomeMethod();
is outlawed by our coding standards, but the following is encouraged in our team because it increases readability:
var list = new List<KeyValuePair<string, double>>();
FillList( list );
foreach( var item in list ) {
DoWork( item );
}
It's not bad, it's more a stylistic thing, which tends to be subjective. It can add inconsistencies, when you do use var and when you don't.
Another case of concern, in the following call you can't tell just by looking at the code the type returned by CallMe:
var variable = CallMe();
That's my main complain against var.
I use var when I declare anonymous delegates in methods, somehow var looks cleaner than if I'd use Func. Consider this code:
var callback = new Func<IntPtr, bool>(delegate(IntPtr hWnd) {
...
});
EDIT: Updated the last code sample based on Julian's input
Var is not like variant at all. The variable is still strongly typed, it's just that you don't press keys to get it that way. You can hover over it in Visual Studio to see the type. If you're reading printed code, it's possible you might have to think a little to work out what the type is. But there is only one line that declares it and many lines that use it, so giving things decent names is still the best way to make your code easier to follow.
Is using Intellisense lazy? It's less typing than the whole name. Or are there things that are less work but don't deserve criticism? I think there are, and var is one of them.
The most likely time you'll need this is for anonymous types (where it is 100% required); but it also avoids repetition for the trivial cases, and IMO makes the line clearer. I don't need to see the type twice for a simple initialization.
For example:
Dictionary<string, List<SomeComplexType<int>>> data = new Dictionary<string, List<SomeComplexType<int>>>();
(please don't edit the hscroll in the above - it kinda proves the point!!!)
vs:
var data = new Dictionary<string, List<SomeComplexType<int>>>();
There are, however, occasions when this is misleading, and can potentially cause bugs. Be careful using var if the original variable and initialized type weren't identical. For example:
static void DoSomething(IFoo foo) {Console.WriteLine("working happily") }
static void DoSomething(Foo foo) {Console.WriteLine("formatting hard disk...");}
// this working code...
IFoo oldCode = new Foo();
DoSomething(oldCode);
// ...is **very** different to this code
var newCode = new Foo();
DoSomething(newCode);
One specific case where var is difficult: offline code reviews, especially the ones done on paper.
You can't rely on mouse-overs for that.
I don't see what the big deal is..
var something = someMethod(); // Type of 'something' not clear <-- not to the compiler!
You still have full intellisense on 'something', and for any ambiguous case you have your unit tests, right? ( do you? )
It's not varchar, it's not dim, and it's certainly not dynamic or weak typing. It is stopping maddnes like this:
List<somethinglongtypename> v = new List<somethinglongtypename>();
and reducing that total mindclutter to:
var v = new List<somethinglongtypename>();
Nice, not quite as nice as:
v = List<somethinglongtypename>();
But then that's what Boo is for.
If someone is using the var keyword because they don't want to "figure out the type", that is definitely the wrong reason. The var keyword doesn't create a variable with a dynamic type, the compiler still has to know the type. As the variable always has a specific type, the type should also be evident in the code if possible.
Good reasons to use the var keyword are for example:
Where it's needed, i.e. to declare a reference for an anonymous type.
Where it makes the code more readable, i.e. removing repetetive declarations.
Writing out the data type often makes the code easier to follow. It shows what data types you are using, so that you don't have to figure out the data type by first figuring out what the code does.
Given how powerful Intellisense is now, I am not sure var is any harder to read than having member variables in a class, or local variables in a method which are defined off the visible screen area.
If you have a line of code such as
IDictionary<BigClassName, SomeOtherBigClassName> nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();
Is is much easier or harder to read than:
var nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();
I think the key thing with VAR is to only use it where appropriate i.e. when doing things in Linq that it facilitates (and probably in other cases).
If you've got a type for something in the then you should use it - not to do so is simple laziness (as opposed to creative laziness which is generally to be encouraged - good programmers oft work very hard to be lazy and could be considered the source of the thing in the first place).
A blanket ban is as bad as abusing the construct in the first place but there does need to be a sensible coding standard.
The other thing to remember is that its not a VB type var in that it can't change types - it is a strongly typed variable its just that the type is inferred (which is why there are people that will argue that its not unreasonable to use it in, say, a foreach but I'd disagree for reasons of both readability and maintainability).
I suspect this one is going to run and run (-:
Murph
Sure, int is easy, but when the variable's type is IEnumerable<MyStupidLongNamedGenericClass<int, string>>, var makes things much easier.
Stolen from the post on this issue at CodingHorror:
Unfortunately, you and everyone else pretty much got it wrong. While I agree with you that redundancy is not a good thing, the better way to solve this issue would have been to do something like the following:
MyObject m = new();
Or if you are passing parameters:
Person p = new("FirstName", "LastName);
Where in the creation of a new object, the compiler infers the type from the left-hand side, and not the right. This has other advantages over "var", in that it could be used in field declarations as well (there are also some other areas that it could be useful as well, but I won't get into it here).
In the end, it just wasn't intended to reduce redundancy. Don't get me wrong, "var" is VERY important in C# for anonymous types/projections, but the use here is just WAY off (and I've been saying this for a long, long time) as you obfuscate the type that is being used. Having to type it twice is too often, but declaring it zero times is too few.
Nicholas Paldino .NET/C# MVP on June 20, 2008 08:00 AM
I guess if your main concern is to have to type less -- then there isn't any argument that's going to sway you from using it.
If you are only going to ever be the person who looks at your code, then who cares? Otherwise, in a case like this:
var people = Managers.People
it's fine, but in a case like this:
var fc = Factory.Run();
it short circuits any immediate type deductions my brain could begin forming from the 'English' of the code.
Otherwise, just use your best judgment and programming 'courtesy' towards others who might have to work on your project.
Using var instead of explicit type makes refactorings much easier (therefore I must contradict the previous posters who meant it made no difference or it was purely "syntactic sugar").
You can change the return type of your methods without changing every file where this method is called. Imagine
...
List<MyClass> SomeMethod() { ... }
...
which is used like
...
IList<MyClass> list = obj.SomeMethod();
foreach (MyClass c in list)
System.Console.WriteLine(c.ToString());
...
If you wanted to refactor SomeMethod() to return an IEnumerable<MySecondClass>, you would have to change the variable declaration (also inside the foreach) in every place you used the method.
If you write
...
var list = obj.SomeMethod();
foreach (var element in list)
System.Console.WriteLine(element.ToString());
...
instead, you don't have to change it.
#aku: One example is code reviews. Another example is refactoring scenarios.
Basically I don't want to go type-hunting with my mouse. It might not be available.
It's a matter of taste. All this fussing about the type of a variable disappears when you get used to dynamically typed languages. That is, if you ever start to like them (I'm not sure if everybody can, but I do).
C#'s var is pretty cool in that it looks like dynamic typing, but actually is static typing - the compiler enforces correct usage.
The type of your variable is not really that important (this has been said before). It should be relatively clear from the context (its interactions with other variables and methods) and its name - don't expect customerList to contain an int...
I am still waiting to see what my boss thinks of this matter - I got a blanket "go ahead" to use any new constructs in 3.5, but what will we do about maintenance?
In your comparison between IEnumerable<int> and IEnumerable<double> you don't need to worry - if you pass the wrong type your code won't compile anyway.
There's no concern about type-safety, as var is not dynamic. It's just compiler magic and any type unsafe calls you make will get caught.
Var is absolutely needed for Linq:
var anonEnumeration =
from post in AllPosts()
where post.Date > oldDate
let author = GetAuthor( post.AuthorId )
select new {
PostName = post.Name,
post.Date,
AuthorName = author.Name
};
Now look at anonEnumeration in intellisense and it will appear something like IEnumerable<'a>
foreach( var item in anonEnumeration )
{
//VS knows the type
item.PostName; //you'll get intellisense here
//you still have type safety
item.ItemId; //will throw a compiler exception
}
The C# compiler is pretty clever - anon types generated separately will have the same generated type if their properties match.
Outside of that, as long as you have intellisense it makes good sense to use var anywhere the context is clear.
//less typing, this is good
var myList = new List<UnreasonablyLongClassName>();
//also good - I can't be mistaken on type
var anotherList = GetAllOfSomeItem();
//but not here - probably best to leave single value types declared
var decimalNum = 123.456m;
I guess it depends on your perspective. I personally have never had any difficulty understanding a piece of code because of var "misuse", and my coworkers and I use it quite a lot all over. (I agree that Intellisense is a huge aid in this regard.) I welcome it as a way to remove repetitive cruft.
After all, if statements like
var index = 5; // this is supposed to be bad
var firstEligibleObject = FetchSomething(); // oh no what type is it
// i am going to die if i don't know
were really that impossible to deal with, nobody would use dynamically typed languages.
I only use var when it's clear to see what type is used.
For example, I would use var in this case, because you can see immediately that x will be of the type "MyClass":
var x = new MyClass();
I would NOT use var in cases like this, because you have to drag the mouse over the code and look at the tooltip to see what type MyFunction returns:
var x = MyClass.MyFunction();
Especially, I never use var in cases where the right side is not even a method, but only a value:
var x = 5;
(because the compiler can't know if I want a byte, short, int or whatever)
To me, the antipathy towards var illustrates why bilingualism in .NET is important. To those C# programmers who have also done VB .NET, the advantages of var are intuitively obvious. The standard C# declaration of:
List<string> whatever = new List<string>();
is the equivalent, in VB .NET, of typing this:
Dim whatever As List(Of String) = New List(Of String)
Nobody does that in VB .NET, though. It would be silly to, because since the first version of .NET you've been able to do this...
Dim whatever As New List(Of String)
...which creates the variable and initializes it all in one reasonably compact line. Ah, but what if you want an IList<string>, not a List<string>? Well, in VB .NET that means you have to do this:
Dim whatever As IList(Of String) = New List(Of String)
Just like you'd have to do in C#, and obviously couldn't use var for:
IList<string> whatever = new List<string>();
If you need the type to be something different, it can be. But one of the basic principles of good programming is reducing redundancy, and that's exactly what var does.
Use it for anonymous types - that's what it's there for. Anything else is a use too far. Like many people who grew up on C, I'm used to looking at the left of the declaration for the type. I don't look at the right side unless I have to. Using var for any old declaration makes me do that all the time, which I personally find uncomfortable.
Those saying 'it doesn't matter, use what you're happy with' are not seeing the whole picture. Everyone will pick up other people's code at one point or another and have to deal with whatever decisions they made at the time they wrote it. It's bad enough having to deal with radically different naming conventions, or - the classic gripe - bracing styles, without adding the whole 'var or not' thing into the mix. The worst case will be where one programmer didn't use var and then along comes a maintainer who loves it, and extends the code using it. So now you have an unholy mess.
Standards are a good thing precisely because they mean you're that much more likely to be able to pick up random code and be able to grok it quickly. The more things that are different, the harder that gets. And moving to the 'var everywhere' style makes a big difference.
I don't mind dynamic typing, and I don't mind implict typing - in languages that are designed for them. I quite like Python. But C# was designed as a statically explicitly-typed language and that's how it should stay. Breaking the rules for anonymous types was bad enough; letting people take that still further and break the idioms of the language even more is something I'm not happy with. Now that the genie is out of the bottle, it'll never go back in. C# will become balkanised into camps. Not good.
Many time during testing, I find myself having code like this:
var something = myObject.SomeProperty.SomeOtherThing.CallMethod();
Console.WriteLine(something);
Now, sometimes, I'll want to see what the SomeOtherThing itself contains, SomeOtherThing is not the same type that CallMethod() returns. Since I'm using var though, I just change this:
var something = myObject.SomeProperty.SomeOtherThing.CallMethod();
to this:
var something = myObject.SomeProperty.SomeOtherThing;
Without var, I'd have to keep changing the declared type on the left hand side as well. I know it's minor, but it's extremely convenient.
For the afficionados that think var saves time, it takes less keystrokes to type:
StringBuilder sb = new StringBuilder();
than
var sb = new StringBuilder();
Count em if you don't believe me...
19 versus 21
I'll explain if I have to, but just try it... (depending on the current state of your intellisense you may have to type a couple more for each one)
And it's true for every type you can think of!!
My personal feeling is that var should never be used except where the type is not known because it reduces recognition readabiltiy in code. It takes the brain longer to recognize the type than a full line. Old timers who understand machine code and bits know exactly what I am talking about. The brain processes in parallel and when you use var you force it to serialize its input. Why would anyone want to make their brain work harder? That's what computers are for.
I split var all over the places, the only questionable places for me are internal short types, e.g. I prefer int i = 3; over var i = 3;
It can certainly make things simpler, from code I wrote yesterday:
var content = new Queue<Pair<Regex, Func<string, bool>>>();
...
foreach (var entry in content) { ... }
This would have be extremely verbose without var.
Addendum: A little time spent with a language with real type inference (e.g. F#) will show just how good compilers are at getting the type of expressions right. It certainly has meant I tend to use var as much as I can, and using an explicit type now indicates that the variable is not of the initialising expression's type.
None, except that you don't have to write the type name twice. http://msdn.microsoft.com/en-us/library/bb383973.aspx

Use of var keyword in C#

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?
For example I rather lazily used var in questionable circumstances, e.g.:-
foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.
More legitimate uses of var are as follows:-
var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.
Interestingly LINQ seems to be a bit of a grey area, e.g.:-
var results = from r in dataContext.SomeTable
select r; // Not *entirely clear* what results will be here.
It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.
It's even worse when it comes to LINQ to objects, e.g.:-
var results = from item in someList
where item != 3
select item;
This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.
There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type.
var does maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
I still think 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> or BindingList<Order> - all I want is to keep that list in memory to iterate over it or get its count or something later on.
Contrast the above declaration with:
ObservableCollection<Order> orders = cust.Orders;
To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection<Order> to IList<Order>) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.
I use var extensively. There has been criticism that this diminishes the readability of the code, but no argument to support that claim.
Admittedly, it may mean that it's not clear what type we are dealing with. So what? This is actually the point of a decoupled design. When dealing with interfaces, you are emphatically not interested in the type a variable has. var takes this much further, true, but I think that the argument remains the same from a readability point of view: The programmer shouldn't actually be interested in the type of the variable but rather in what a variable does. This is why Microsoft also calls type inference “duck typing.”
So, what does a variable do when I declare it using var? Easy, it does whatever IntelliSense tells me it does. Any reasoning about C# that ignores the IDE falls short of reality. In practice, every C# code is programmed in an IDE that supports IntelliSense.
If I am using a var declared variable and get confused what the variable is there for, there's something fundamentally wrong with my code. var is not the cause, it only makes the symptoms visible. Don't blame the messenger.
Now, the C# team has released a coding guideline stating that var should only be used to capture the result of a LINQ statement that creates an anonymous type (because here, we have no real alternative to var). Well, screw that. As long as the C# team doesn't give me a sound argument for this guideline, I am going to ignore it because in my professional and personal opinion, it's pure baloney. (Sorry; I've got no link to the guideline in question.)
Actually, there are some (superficially) good explanations on why you shouldn't use var but I still believe they are largely wrong. Take the example of “searchabililty”: the author claims that var makes it hard to search for places where MyType is used. Right. So do interfaces. Actually, why would I want to know where the class is used? I might be more interested in where it is instantiated and this will still be searchable because somewhere its constructor has to be invoked (even if this is done indirectly, the type name has to be mentioned somewhere).
Var, in my opinion, in C# is a good thingtm. Any variable so typed is still strongly typed, but it gets its type from the right-hand side of the assignment where it is defined. Because the type information is available on the right-hand side, in most cases, it's unnecessary and overly verbose to also have to enter it on the left-hand side. I think this significantly increases readability without decreasing type safety.
From my perspective, using good naming conventions for variables and methods is more important from a readability perspective than explicit type information. If I need the type information, I can always hover over the variable (in VS) and get it. Generally, though, explicit type information shouldn't be necessary to the reader. For the developer, in VS you still get Intellisense, regardless of how the variable is declared. Having said all of that, there may still be cases where it does make sense to explicitly declare the type -- perhaps you have a method that returns a List<T>, but you want to treat it as an IEnumerable<T> in your method. To ensure that you are using the interface, declaring the variable of the interface type can make this explicit. Or, perhaps, you want to declare a variable without an initial value -- because it immediately gets a value based on some condition. In that case you need the type. If the type information is useful or necessary, go ahead and use it. I feel, though, that typically it isn't necessary and the code is easier to read without it in most cases.
Neither of those is absolutely true; var can have both positive and negative effects on readability. In my opinion, var should be used when either of the following is true:
The type is anonymous (well, you don't have any choice here, as it must be var in this case)
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.
From Eric Lippert, a Senior Software Design Engineer on the C# team:
Why was the var keyword introduced?
There are two reasons, one which
exists today, one which will crop up
in 3.0.
The first reason is that this code is
incredibly ugly because of all the
redundancy:
Dictionary<string, List<int>> mylists = new Dictionary<string, List<int>>();
And that's a simple example – I've
written worse. Any time you're forced
to type exactly the same thing twice,
that's a redundancy that we can
remove. Much nicer to write
var mylists = new Dictionary<string,List<int>>();
and let the compiler figure out what
the type is based on the assignment.
Second, C# 3.0 introduces anonymous
types. Since anonymous types by
definition have no names, you need to
be able to infer the type of the
variable from the initializing
expression if its type is anonymous.
Emphasis mine. The whole article, C# 3.0 is still statically typed, honest!, and the ensuing series are pretty good.
This is what var is for. Other uses probably will not work so well. Any comparison to JScript, VBScript, or dynamic typing is total bunk. Note again, var is required in order to have certain other features work in .NET.
I think the use of var should be coupled with wisely-chosen variable names.
I have no problem using var in a foreach statement, provided it's not like this:
foreach (var c in list) { ... }
If it were more like this:
foreach (var customer in list) { ... }
... then someone reading the code would be much more likely to understand what "list" is. If you have control over the name of the list variable itself, that's even better.
The same can apply to other situations. This is pretty useless:
var x = SaveFoo(foo);
... but this makes sense:
var saveSucceeded = SaveFoo(foo);
Each to his own, I guess. I've found myself doing this, which is just insane:
var f = (float)3;
I need some sort of 12-step var program. My name is Matt, and I (ab)use var.
We've adopted the ethos "Code for people, not machines", based on the assumption that you spend multiple times longer in maintenance mode than on new development.
For me, that rules out the argument that the compiler "knows" what type the variable is - sure, you can't write invalid code the first time because the compiler stops your code from compiling, but when the next developer is reading the code in 6 months time they need to be able to deduce what the variable is doing correctly or incorrectly and quickly identify the cause of issues.
Thus,
var something = SomeMethod();
is outlawed by our coding standards, but the following is encouraged in our team because it increases readability:
var list = new List<KeyValuePair<string, double>>();
FillList( list );
foreach( var item in list ) {
DoWork( item );
}
It's not bad, it's more a stylistic thing, which tends to be subjective. It can add inconsistencies, when you do use var and when you don't.
Another case of concern, in the following call you can't tell just by looking at the code the type returned by CallMe:
var variable = CallMe();
That's my main complain against var.
I use var when I declare anonymous delegates in methods, somehow var looks cleaner than if I'd use Func. Consider this code:
var callback = new Func<IntPtr, bool>(delegate(IntPtr hWnd) {
...
});
EDIT: Updated the last code sample based on Julian's input
Var is not like variant at all. The variable is still strongly typed, it's just that you don't press keys to get it that way. You can hover over it in Visual Studio to see the type. If you're reading printed code, it's possible you might have to think a little to work out what the type is. But there is only one line that declares it and many lines that use it, so giving things decent names is still the best way to make your code easier to follow.
Is using Intellisense lazy? It's less typing than the whole name. Or are there things that are less work but don't deserve criticism? I think there are, and var is one of them.
The most likely time you'll need this is for anonymous types (where it is 100% required); but it also avoids repetition for the trivial cases, and IMO makes the line clearer. I don't need to see the type twice for a simple initialization.
For example:
Dictionary<string, List<SomeComplexType<int>>> data = new Dictionary<string, List<SomeComplexType<int>>>();
(please don't edit the hscroll in the above - it kinda proves the point!!!)
vs:
var data = new Dictionary<string, List<SomeComplexType<int>>>();
There are, however, occasions when this is misleading, and can potentially cause bugs. Be careful using var if the original variable and initialized type weren't identical. For example:
static void DoSomething(IFoo foo) {Console.WriteLine("working happily") }
static void DoSomething(Foo foo) {Console.WriteLine("formatting hard disk...");}
// this working code...
IFoo oldCode = new Foo();
DoSomething(oldCode);
// ...is **very** different to this code
var newCode = new Foo();
DoSomething(newCode);
One specific case where var is difficult: offline code reviews, especially the ones done on paper.
You can't rely on mouse-overs for that.
I don't see what the big deal is..
var something = someMethod(); // Type of 'something' not clear <-- not to the compiler!
You still have full intellisense on 'something', and for any ambiguous case you have your unit tests, right? ( do you? )
It's not varchar, it's not dim, and it's certainly not dynamic or weak typing. It is stopping maddnes like this:
List<somethinglongtypename> v = new List<somethinglongtypename>();
and reducing that total mindclutter to:
var v = new List<somethinglongtypename>();
Nice, not quite as nice as:
v = List<somethinglongtypename>();
But then that's what Boo is for.
If someone is using the var keyword because they don't want to "figure out the type", that is definitely the wrong reason. The var keyword doesn't create a variable with a dynamic type, the compiler still has to know the type. As the variable always has a specific type, the type should also be evident in the code if possible.
Good reasons to use the var keyword are for example:
Where it's needed, i.e. to declare a reference for an anonymous type.
Where it makes the code more readable, i.e. removing repetetive declarations.
Writing out the data type often makes the code easier to follow. It shows what data types you are using, so that you don't have to figure out the data type by first figuring out what the code does.
Given how powerful Intellisense is now, I am not sure var is any harder to read than having member variables in a class, or local variables in a method which are defined off the visible screen area.
If you have a line of code such as
IDictionary<BigClassName, SomeOtherBigClassName> nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();
Is is much easier or harder to read than:
var nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();
I think the key thing with VAR is to only use it where appropriate i.e. when doing things in Linq that it facilitates (and probably in other cases).
If you've got a type for something in the then you should use it - not to do so is simple laziness (as opposed to creative laziness which is generally to be encouraged - good programmers oft work very hard to be lazy and could be considered the source of the thing in the first place).
A blanket ban is as bad as abusing the construct in the first place but there does need to be a sensible coding standard.
The other thing to remember is that its not a VB type var in that it can't change types - it is a strongly typed variable its just that the type is inferred (which is why there are people that will argue that its not unreasonable to use it in, say, a foreach but I'd disagree for reasons of both readability and maintainability).
I suspect this one is going to run and run (-:
Murph
Sure, int is easy, but when the variable's type is IEnumerable<MyStupidLongNamedGenericClass<int, string>>, var makes things much easier.
Stolen from the post on this issue at CodingHorror:
Unfortunately, you and everyone else pretty much got it wrong. While I agree with you that redundancy is not a good thing, the better way to solve this issue would have been to do something like the following:
MyObject m = new();
Or if you are passing parameters:
Person p = new("FirstName", "LastName);
Where in the creation of a new object, the compiler infers the type from the left-hand side, and not the right. This has other advantages over "var", in that it could be used in field declarations as well (there are also some other areas that it could be useful as well, but I won't get into it here).
In the end, it just wasn't intended to reduce redundancy. Don't get me wrong, "var" is VERY important in C# for anonymous types/projections, but the use here is just WAY off (and I've been saying this for a long, long time) as you obfuscate the type that is being used. Having to type it twice is too often, but declaring it zero times is too few.
Nicholas Paldino .NET/C# MVP on June 20, 2008 08:00 AM
I guess if your main concern is to have to type less -- then there isn't any argument that's going to sway you from using it.
If you are only going to ever be the person who looks at your code, then who cares? Otherwise, in a case like this:
var people = Managers.People
it's fine, but in a case like this:
var fc = Factory.Run();
it short circuits any immediate type deductions my brain could begin forming from the 'English' of the code.
Otherwise, just use your best judgment and programming 'courtesy' towards others who might have to work on your project.
Using var instead of explicit type makes refactorings much easier (therefore I must contradict the previous posters who meant it made no difference or it was purely "syntactic sugar").
You can change the return type of your methods without changing every file where this method is called. Imagine
...
List<MyClass> SomeMethod() { ... }
...
which is used like
...
IList<MyClass> list = obj.SomeMethod();
foreach (MyClass c in list)
System.Console.WriteLine(c.ToString());
...
If you wanted to refactor SomeMethod() to return an IEnumerable<MySecondClass>, you would have to change the variable declaration (also inside the foreach) in every place you used the method.
If you write
...
var list = obj.SomeMethod();
foreach (var element in list)
System.Console.WriteLine(element.ToString());
...
instead, you don't have to change it.
#aku: One example is code reviews. Another example is refactoring scenarios.
Basically I don't want to go type-hunting with my mouse. It might not be available.
It's a matter of taste. All this fussing about the type of a variable disappears when you get used to dynamically typed languages. That is, if you ever start to like them (I'm not sure if everybody can, but I do).
C#'s var is pretty cool in that it looks like dynamic typing, but actually is static typing - the compiler enforces correct usage.
The type of your variable is not really that important (this has been said before). It should be relatively clear from the context (its interactions with other variables and methods) and its name - don't expect customerList to contain an int...
I am still waiting to see what my boss thinks of this matter - I got a blanket "go ahead" to use any new constructs in 3.5, but what will we do about maintenance?
In your comparison between IEnumerable<int> and IEnumerable<double> you don't need to worry - if you pass the wrong type your code won't compile anyway.
There's no concern about type-safety, as var is not dynamic. It's just compiler magic and any type unsafe calls you make will get caught.
Var is absolutely needed for Linq:
var anonEnumeration =
from post in AllPosts()
where post.Date > oldDate
let author = GetAuthor( post.AuthorId )
select new {
PostName = post.Name,
post.Date,
AuthorName = author.Name
};
Now look at anonEnumeration in intellisense and it will appear something like IEnumerable<'a>
foreach( var item in anonEnumeration )
{
//VS knows the type
item.PostName; //you'll get intellisense here
//you still have type safety
item.ItemId; //will throw a compiler exception
}
The C# compiler is pretty clever - anon types generated separately will have the same generated type if their properties match.
Outside of that, as long as you have intellisense it makes good sense to use var anywhere the context is clear.
//less typing, this is good
var myList = new List<UnreasonablyLongClassName>();
//also good - I can't be mistaken on type
var anotherList = GetAllOfSomeItem();
//but not here - probably best to leave single value types declared
var decimalNum = 123.456m;
I guess it depends on your perspective. I personally have never had any difficulty understanding a piece of code because of var "misuse", and my coworkers and I use it quite a lot all over. (I agree that Intellisense is a huge aid in this regard.) I welcome it as a way to remove repetitive cruft.
After all, if statements like
var index = 5; // this is supposed to be bad
var firstEligibleObject = FetchSomething(); // oh no what type is it
// i am going to die if i don't know
were really that impossible to deal with, nobody would use dynamically typed languages.
I only use var when it's clear to see what type is used.
For example, I would use var in this case, because you can see immediately that x will be of the type "MyClass":
var x = new MyClass();
I would NOT use var in cases like this, because you have to drag the mouse over the code and look at the tooltip to see what type MyFunction returns:
var x = MyClass.MyFunction();
Especially, I never use var in cases where the right side is not even a method, but only a value:
var x = 5;
(because the compiler can't know if I want a byte, short, int or whatever)
To me, the antipathy towards var illustrates why bilingualism in .NET is important. To those C# programmers who have also done VB .NET, the advantages of var are intuitively obvious. The standard C# declaration of:
List<string> whatever = new List<string>();
is the equivalent, in VB .NET, of typing this:
Dim whatever As List(Of String) = New List(Of String)
Nobody does that in VB .NET, though. It would be silly to, because since the first version of .NET you've been able to do this...
Dim whatever As New List(Of String)
...which creates the variable and initializes it all in one reasonably compact line. Ah, but what if you want an IList<string>, not a List<string>? Well, in VB .NET that means you have to do this:
Dim whatever As IList(Of String) = New List(Of String)
Just like you'd have to do in C#, and obviously couldn't use var for:
IList<string> whatever = new List<string>();
If you need the type to be something different, it can be. But one of the basic principles of good programming is reducing redundancy, and that's exactly what var does.
Use it for anonymous types - that's what it's there for. Anything else is a use too far. Like many people who grew up on C, I'm used to looking at the left of the declaration for the type. I don't look at the right side unless I have to. Using var for any old declaration makes me do that all the time, which I personally find uncomfortable.
Those saying 'it doesn't matter, use what you're happy with' are not seeing the whole picture. Everyone will pick up other people's code at one point or another and have to deal with whatever decisions they made at the time they wrote it. It's bad enough having to deal with radically different naming conventions, or - the classic gripe - bracing styles, without adding the whole 'var or not' thing into the mix. The worst case will be where one programmer didn't use var and then along comes a maintainer who loves it, and extends the code using it. So now you have an unholy mess.
Standards are a good thing precisely because they mean you're that much more likely to be able to pick up random code and be able to grok it quickly. The more things that are different, the harder that gets. And moving to the 'var everywhere' style makes a big difference.
I don't mind dynamic typing, and I don't mind implict typing - in languages that are designed for them. I quite like Python. But C# was designed as a statically explicitly-typed language and that's how it should stay. Breaking the rules for anonymous types was bad enough; letting people take that still further and break the idioms of the language even more is something I'm not happy with. Now that the genie is out of the bottle, it'll never go back in. C# will become balkanised into camps. Not good.
Many time during testing, I find myself having code like this:
var something = myObject.SomeProperty.SomeOtherThing.CallMethod();
Console.WriteLine(something);
Now, sometimes, I'll want to see what the SomeOtherThing itself contains, SomeOtherThing is not the same type that CallMethod() returns. Since I'm using var though, I just change this:
var something = myObject.SomeProperty.SomeOtherThing.CallMethod();
to this:
var something = myObject.SomeProperty.SomeOtherThing;
Without var, I'd have to keep changing the declared type on the left hand side as well. I know it's minor, but it's extremely convenient.
For the afficionados that think var saves time, it takes less keystrokes to type:
StringBuilder sb = new StringBuilder();
than
var sb = new StringBuilder();
Count em if you don't believe me...
19 versus 21
I'll explain if I have to, but just try it... (depending on the current state of your intellisense you may have to type a couple more for each one)
And it's true for every type you can think of!!
My personal feeling is that var should never be used except where the type is not known because it reduces recognition readabiltiy in code. It takes the brain longer to recognize the type than a full line. Old timers who understand machine code and bits know exactly what I am talking about. The brain processes in parallel and when you use var you force it to serialize its input. Why would anyone want to make their brain work harder? That's what computers are for.
I split var all over the places, the only questionable places for me are internal short types, e.g. I prefer int i = 3; over var i = 3;
It can certainly make things simpler, from code I wrote yesterday:
var content = new Queue<Pair<Regex, Func<string, bool>>>();
...
foreach (var entry in content) { ... }
This would have be extremely verbose without var.
Addendum: A little time spent with a language with real type inference (e.g. F#) will show just how good compilers are at getting the type of expressions right. It certainly has meant I tend to use var as much as I can, and using an explicit type now indicates that the variable is not of the initialising expression's type.
None, except that you don't have to write the type name twice. http://msdn.microsoft.com/en-us/library/bb383973.aspx

Should I *always* favour implictly typed local variables in C# 3.0?

Resharper certainly thinks so, and out of the box it will nag you to convert
Dooberry dooberry = new Dooberry();
to
var dooberry = new Dooberry();
Is that really considered the best style?
It's of course a matter of style, but I agree with Dare: C# 3.0 Implicit Type Declarations: To var or not to var?. I think using var instead of an explicit type makes your code less readable.In the following code:
var result = GetUserID();
What is result? An int, a string, a GUID? Yes, it matters, and no, I shouldn't have to dig through the code to know. It's especially annoying in code samples.
Jeff wrote a post on this, saying he favors var. But that guy's crazy!
I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question.
I use it only when it's clearly obvious what var is.
clear to me:
XmlNodeList itemList = rssNode.SelectNodes("item");
var rssItems = new RssItem[itemList.Count];
not clear to me:
var itemList = rssNode.SelectNodes("item");
var rssItems = new RssItem[itemList.Count];
The best summary of the answer I've seen to this is Eric Lippert's comment, which essentially says you should use the concrete type if it's important what the type is, but not to otherwise. Essentially type information should be reserved for places where the type is important.
The standard at my company is to use var everywhere, which we came to after reading various recommendations and then spending some time trying it out to see whether the lack of annotated type information was a help or a hindrance. We felt it was a help.
Most of the recommendations people have linked to (e.g. Dare's one) are recommendations made by people who have never tried coding using var instead of the concrete type. This makes the recommendations all but worthless because they aren't speaking from experience, they're merely extrapolating.
The best advice I can give you is to try it for yourself, and see what works for you and your team.
#jongalloway - var doesn't necessarily make your code more unreadable.
var myvariable = DateTime.Now
DateTime myvariable = DateTime.Now;
The first is just as readable as the second and requires less work
var myvariable = ResultFromMethod();
here, you have a point, var could make the code less readable. I like var because if I change a decimal to a double, I don't have to go change it in a bunch of places (and don't say refactor, sometimes I forget, just let me var!)
EDIT: just read the article, I agree. lol.
There was a good discussion on this # Coding Horror
Personally I try to keep its use to a minimum, I have found it hurts readability especially when assigning a variable from a method call.
I have a feeling this will be one of the most popular questions asked over time on Stack Overflow. It boils down to preference. Whatever you think is more readable. I prefer var when the type is defined on the right side because it is terser. When I'm assigning a variable from a method call, I use the explicit type declaration.
It only make sense, when you don't know the type in advance.
In C# 9.0 there is a new way to initialize a class by Target-typed new expressions.
You can initialize the class like this:
Dooberry dooberry = new();
Personally, I like it more than using a var and it is more readable for me.
Regarding calling a method I think it is up to you. Personally, I prefer to specify the type because I think it is more readable this way:
Dooberry dooberry = GetDooberry();
In some cases, it is very clear what the type is, in this case, I use var:
var now = DateTime.Now;
One of the advantages of a tool like ReSharper is that you can write the code however you like and have it reformat to something more maintainable afterward. I have R# set to always reformat such that the actual type in use is visible, however, when writing code I nearly always type 'var'.
Good tools let you have the best of both worlds.
John.
"Best style" is subjective and varies depending on context.
Sometimes it is way easier to use 'var' instead of typing out some hugely long class name, or if you're unsure of the return type of a given function. I find I use 'var' more when mucking about with Linq, or in for loop declarations.
Other times, using the full class name is more helpful as it documents the code better than 'var' does.
I feel that it's up to the developer to make the decision. There is no silver bullet. No "one true way".
Cheers!
I'm seeing a pattern for stackoverflow
success: dig up old CodingHorror posts
and (Jeopardy style) phrase them in
terms of a question.
I plead innocent! But you're right, this seemed to be a relatively popular little question.
There's a really good MSDN article on this topic and it outlines some cases where you can't use var:
The following restrictions apply to implicitly-typed variable declarations:
var can only be used when a local variable is declared and initialized
in the same statement; the variable
cannot be initialized to null, or to a
method group or an anonymous function.
var cannot be used on fields at class scope.
Variables declared by using var cannot be used in the initialization
expression. In other words, this
expression is legal: int i = (i = 20);
but this expression produces a
compile-time error: var i = (i = 20);
Multiple implicitly-typed variables cannot be initialized in the same
statement.
If a type named var is in scope, then the var keyword will resolve to
that type name and will not be treated
as part of an implicitly typed local
variable declaration.
I would recommend checking it out to understand the full implications of using var in your code.
No not always but I would go as far as to say a lot of the time. Type declarations aren't much more useful than Hungarian notation ever was. You still have the same problem that types are subject to change and as much as refactoring tools are helpful for that it's not ideal compared to not having to change where a type is specified except in a single place, which follows the Don't Repeat Yourself principle.
Any single line statement where a type's name can be specified for both a variable and its value should definitely use var, especially when it's a long Generic<OtherGeneric< T,U,V>, Dictionary< X, Y>>>

Categories