Use of var keyword in C#
Asked Answered
C

86

405

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.

Cumquat answered 3/9, 2008 at 11:30 Comment(15)
I've blogged about it before, and there is some discussion in comments too.Quote
This question seems to have been asked and discussed before, here: C# - Do you use “var”? At the risk of repeating myself, I'll link to my answer in that linked question, which, given the upvotes, seems to be a fairly general consensus for quite a few people (but also sparked some interesting comments!): My Answer EDIT: Well, seems this particular question actually pre-dates the one I linked to [smacks forehead], however, I'll leave this here since theLatvina
Here is a quite nice article why it is a good idea to use var.Boxing
In LINQ, var must be used because you can't always know what you'll be getting out of the query.Homelike
Pedant moment - var is not a keyowrd ... it is a contextual data token ;)Caper
Using var is fine, but "I don't have to figure out the type" seems like a very bad reason to use it... you're supposed to know what the type is, var is just a shortcut to avoid typing itForeground
@Thomas Levesque: That struck me as being a bad reason too. I have no problems with shortcuts. I'd never give up my IDE for notepad.Erudition
var i = 0; == fail! var c = new CrazyFrigginLongClassName(); == win!Coldhearted
"Var also reminds me of the VB/VBA variant type. It also had its place. I recall (from many years ago) its usage being less-than-desirable type and it was rather resource hungry." <- shows this is a baiting question as the 'var' type of C# has nothing to do with the VB/VBA variant type.Donelson
var readabilityBeDamned = true;Hemophilia
What's the difference between var and C++0x's auto? Without bothering to look it up, I don't see any.Depth
I wrote about var and dynamic a while back, itcrowd.be/post/C-40-About-the-dynamic-keyword.aspx In my opinion it improves readability.... and removes redundance... a lot of people seem to confuse var from C# with dynamically typed keywords of the same name in other languages such as JavaScriptStreamlined
The problem with all the examples stated here is that we're looking at ONE line of code. When I see line after line of "var" declarations, one after the other, it gets out of hand. Readability is subjective, but I find var abused far more than used respectably.Varian
@sixlettervariables: The difference is that the the VB variant was accepting any types during execution. The C# var causes an explicit type declaration at compile time, and accepts only usage as one type in the lifetime of the variable. Therefore the C# var is practacally the same as explicit declaration in the compiled executable.Blench
@awe: I'm aware of the distinction, I was pointing out the inflammatory language in the original question.Donelson
W
292

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.

Whisky answered 3/9, 2008 at 11:30 Comment(11)
I like having the explicit type in front of me when I'm reading code. How do I know what "cust.Orders" is here without the type? Yes, I could hover my mouse over to find out, but why should I have to? :)Laritalariviere
But the point is that in general it doesn't matter. Provided cust.Orders is something you can enumerate (eg foreach over) then it doesn't matter what type it is. The extra code just gets in the way of reading the intent.Whisky
Yeah I frequently end up changing generics when doing some rough outlines.Transfigure
But if you only require that cust.Orders is "something you can enumerate" then doesn't declaring it as an IEnumerable<Order> make that requirement explicit and clear? Declaring it as var means you effectively lose that requirement.Oratory
I think this is a bit of a simplification of the issue. True, that if all you want to do is iterate over the list, then it doesn't matter... but, in your example, if it's BindingList<Order> then it tells you, immediately that it will support binding to a UI control without trouble - which is important info imo.Raid
If you're really in a situation where listing what interface you're getting is 'just noise,' then you probably don't need to be getting that interface. But you should be using the object in code later on, so clearly the interface is not irrelevant. (Is it strange if I think like this?)Intertidal
Whilst it is a personal decision I do not agree that the type name is just noise, it is all about maintainability for me, long after you are gone lesser mortals will have to read your code, using var where you CAN use a strong type name is in my opinion wrong. I didn't used to beleive that but after a while of using the style you have above I became convinced.Catercorner
@jon and how would IEnumerbal orders = cust.Orders foreach(var order in orders) make a difference? the only thing IEnumerable says is that you can put it in a foreach but you already knew that from the line belowTacho
"the only thing IEnumerable says is that you can put it in a foreach" - it also expresses the intention that the only thing you can do is enumerate. Using var gives access to and intellisense for public members of the concrete collection type.Happiness
@Happiness - And if you want to use any of these public members, which are not part of IEnumerable, then it would help a reader much to explicitly declare the variable using that particular type.Maretz
I just realized var changed the way I write code. I started writing faster, in a good way.Revue
R
167

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).

Reside answered 3/9, 2008 at 11:30 Comment(13)
In any decent IDE, you don't use a text search to obtain class usage, you get the IDE to do it based on it's parse tree or however else it identifies the types of objects. Since we're talking about static typing, this will find everything but the anonymous types.Melee
I agree with Konrad. I've used var in other places than LINQ statements and I find it to be quite useful.Absorbed
I agree. var makes my code much easier to maintain. I would understand the arguments against it if it wasn't strong typed. But it is. Also using visual studio why do I care to know what the class is on the declaration. I can hover or just use IntelliSense and it also makes it much easier to prototype and refactor. To me less code and less clutter equals less bugs.Brasilin
I'd hate to inherit 100k lines of source with no documentation and liberal use of var. Especially if you combine var with less-than-helpful variable names. I could see it being helpful when illustrating a point (or dealing with anonymous types) but in production code?Bolanger
Arnshea: well you've already pointed to the real problem there: the useless variable names, and the missing documentation. I really fail to see what var contributes to the confusion. Certainly, there may be cases where it is important to emphasize the type/size of a variable (e.g. low-level bit operations). That's fine: nobody ever claimed that var should be used exclusively. The rule is simple: if it really causes confusion, don't use it.Reside
Every example opposed to var I've seen assumes that the programmer will be using meaningless variable names. But maybe this is why var is better than explicitly specifying a type: It forces the programmer to come up with good variable names.Cellulose
Microsoft also calls type inference “duck typing.” — do they really? I'd be shocked...Lambaste
@Anton: sorry, I can't give you a source for that claim (though searching in the MSDN library should turn something up) but yes, Microsoft used this excessively in their previews of the new var keyword. Perhaps it got mangled by marketing but in this case, I doubt it.Reside
It's possible that the guideline you refer to (which I recall as well) got sent down the memory hole. I remember that happening when Microsoft published a really terrible article, supposedly on TDD, which in fact described the opposite of TDD.Cellulose
"... hard to search for places where MyType is used" - and sometimes much easier to find places where it is initially instantiated, or its static methods are called, because other usages (such as assigning from a method or some property call) are filtered out. After that I can further search for usages of the particular property or method, if I need to.Mcmillin
I believe duck-typing is a recognised concept. I certainly have heard it used to describe typing systems in other frameworks.Yorktown
@ElRonnoco We know that. The problem is that duck typing is something different, and Microsoft used the term wrongly.Reside
@KonradRudolph Ah, sorry, I misunderstood.Yorktown
Z
118

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.

Zareba answered 19/5, 2010 at 13:50 Comment(8)
I agree overall. The key point here in my opinion is to be certain that intent is clear. If it isn't clear to the majority developers on the team, then it is detrimental, not helpful. That said, I personally am a HUGE fan of this, but have had to rein myself in a bit when other devs on my team have had trouble determining my intent. Go figure.Ternan
Eh, I find it easier to read when the type is on the left. Using ReSharper, I don't have to retype the type on the right anyways, so it doesn't bother me.Ashwell
@BlueRaja - I find that using good variable names usually eliminates the need to bother with the actual type anyway for understanding. Intellisense is still available on "var" defined variables, so I don't need to know the type to choose a method/property on it when coding.Zareba
It is not so much about when you are coding as it is when you have to read the code.Ashwell
@BlueRaja -- that's where using good variable names is important. You shouldn't need to know the type if the variable is named appropriately. If, for some reason, I do need to know the type, all I have to do is hover over the variable name to get it.Zareba
I don't agree with this: "Because the type information is available on the right-hand side, in most cases" I would challenge whether that is really true. Looking through my teams codes we don't go around ensuring that the return type is verbatim in the method names. Using an expclicit type is more readable and more resilient to runtime bugs.Japhetic
@Anthony - 1) I never said that you couldn't use it in cases where the type information is valuable and isn't available. 2) Good naming, both with variable names and method names, is (from a reading/understanding perspective) more important than type information anyway. If you regularly need the type in addition to the variable/method names to make sense of the code you probably have bigger problems than using or not using var.Zareba
I must just be on thick side then, I need to good Method and variable names and an understanding of the types being operated on to be able to properly understand the code I'm reading. I think you are right though it is symptomatic of bigger problems. One of trust. To be sure that the code is doing what it appears to be doing you need to be sure of the types being used.Japhetic
F
91

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:

  1. The type is anonymous (well, you don't have any choice here, as it must be var in this case)
  2. 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.

Fernandina answered 19/5, 2010 at 13:49 Comment(11)
agree on both, though I have long restrictions over the second case, if a type is that long the it's usually a generic type with lots of nested generic arguments, in that case a strongly typed "ShortType equivalent to TypeWithAReallyLongNameTheresNoSenseRepeating" makes more senseWarrantable
I have no desire to start a religious war, but I personnaly tend to disagree with Ion. I would much prefer a very long, but very precise type name (ala Uncle Bob Martin) than an abbreviated and possibly ambiguous shorter type name. I will add the caveat that I DON'T agree with artificially inflating the length of the name either. If 5 characters creates a concise name that clearly shows intent, then use 5 and not 25.Ternan
@Steve: I have to agree with you; creating a "short type" (which I assume you mean as inheriting from the specific generic type solely for the purpose of shortening the name) is not a good practice; it will require you to duplicate and pass through any constructors from the generic type, as well as preventing you from passing a different type that inherits from the generic type to the function. You're using inheritance like a typedef when it isn't.Fernandina
@Steve: I guess you are refering to something like: List<KeyValuePair<string, Dictionary<MyClassName, AnotherComplexType>>> list = new List<KeyValuePair<string, Dictionary<MyClassName, AnotherComplexType>>>(); In this case, use I would use var and wrap the horrible mess of tags into a class that actually makes sense to me. var list = new ListOfComplexStuff(); I do agree with the answer that you should refrain from using var unless it does improve readabililty. Readability > Less keypresses.Nesta
Use var when the type is obvious? Maybe, but the true gain is when the type doesn't matter. If you're doing things like var customers = whatever; var query = from c in customers select stuff it doesn't matter what the exact type of 'customers' is. It's obvious how you can use it, and that's enough. And if the actual type is cumbersome, it's worthwhile to suppress it.Illene
@Kristoffer: I can understand wanting to eliminate the mess of tags, but wrapping them into a class is not (IMO) an acceptable alternative, as you then cut off the possibility of any other (legitimate) child class of that generic type from being a valid parameter. I would rather use an using ShortType = LongGenericType<A,B,C> directive at the top of a file, since that gives the same readability, doesn't require that you recreate the constructors, and doesn't eliminate child classes from being candidates.Fernandina
@Joren: The true gain is when it's more readable. If the type truly doesn't matter, then it's probably more readable. If the type matters but is obvious from the inferrence source, then it's probably more readable.Fernandina
@Steve Brouillard, Steve, that's actually my reason as well, but I prefer a shorter name and the type to complement the variable name, e.g. var iPhoneApplication = ..., vs. IPhoneApplication app =... .Warrantable
@Illene - Exactly. I shouldn't care what type a variable of customer is. The name is descriptive enough to know what you can roughly do with it.Halland
@Adam Robinson: You are right, readability is the end goal. And when the type is obvious, indeed var can improve things. My point shouldn't be to the exclusion of yours – I definitely agree with your entire answer – I just used yours as a hook-in for adding a third point. 'True gain' was an exaggeration.Illene
I think most of us commenting here are on the same page.Ternan
M
68

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.

Melee answered 3/9, 2008 at 11:30 Comment(3)
I find Lippert's argument odd. No one types the second class name, they let Intellisense write it for them, but then he turns around and claims that var is better because the compiler/Intellisense works it out. You can't have it both ways!Lucia
The C# team doesn't control intellisense, they control the compiler. In any event that's not the main issue. I don't think var would have made the 100 points on saving typing alone.Melee
@Dustman: var doesn't save typing at all. It makes you write more!Laughlin
W
53

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.

Whisky answered 3/9, 2008 at 11:30 Comment(5)
Well the only thing wrong with "var f = (float)3;" is that it should be "var f = 3f" or "var f = 3.0 (cause single precision sucks)".Oni
Heh yeah 3f or 3.0 is the way to go! Us var maniacs have to stick together!Whisky
The real problem in that first example is "list", not "c". "list" of what? "list" should be renamed to "customers", or "customersWhoOweMoney", or "currentCustomers", or something far more descriptive. And once you have that, the "c" can stay as-is, because you already know what it'll contain.Cellulose
Hi Matt! My name is Kenny and I'm a varaddict.Zygospore
var MattHamil = "Luke Skywalker"; //stripped a ton out of itGest
P
40

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 ); 
}
Pacesetter answered 3/9, 2008 at 11:30 Comment(3)
I've found that ("Code for people, not machines") to be an excellent guideline - following it can result in better code and helps avoid premature optimization.Madaih
I don't get var list = new KeyValuePair<string, double>? For me a list can have more than on thing.Oaken
"Code for people, not machines" - amen.Europa
W
39

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

Warrantable answered 19/5, 2010 at 13:48 Comment(13)
But do you really need to know the type right there at that line? You know that CallMe returns something; isn't it enough to know that a local variable named variable is created? Unless you expand your example, this isn't a very solid complaint, IMO.Foulard
knowing the type lets you make more sense out of any code below the initialization, you automatically know "that code can call that or that", and by having a nice name for the variable you make sense of the code easierWarrantable
But you don't need to know the type in order to read the code. If you see, for example, variable.MyMethod(), you know that the code calls the MyMethod method on whatever type variable happens to be. You don't need to know what MyMethod does at that point, because what you're only concerned with is the fact that the code calls it. Let's assume that you're reading the code for the Very First Time (tm). Even if you knew the type of variable at the declaration, odds are you don't know what that type is or does. You have to go look it up either way, so why be verbose about it?Foulard
It's not about not being verbose, it's about not letting the compiler do the syntax sugar for you. Consider this: var getter..., now this Func<object> getter..., with the second you know you don't have to provide any parameters and what it returns. You know from the start "what to do" and can make decisions faster, when designing something or refactoring. Having all the information at hand is more important than a few more characters. This only can be appreciated when you're working with lots of code.Warrantable
Since we are all talking about visual studio anyway, what's the big deal about hovering your mouse over the variable for a second and just seeing what type is it? Much better than running to the declaration anyway.Marylynnmarylynne
Agree and don't, it's subjective... :)Warrantable
On the contrary, I work with lots of code all the time, and I always prefer var. In your Func<object> example, you can tell from the context of the code (based on the fact that it is called later using getter()) that it's a callable item, either a Func or a delegate. The point is that you can tell from the context, so it's not necessary to have it declared upfront. Planning a refactor is different; yes, you need all the infos when you're planning something like that. But you can obtain it by other means, particularly intellisense, so you don't need it written down right there.Foulard
Generic variable and function names (variable, CallMe) make bad examples. However, if CallMe() was a function in some kind of a "phone application", then var call = CallMe(); .... call.HangUp(); would make much more sense.Venison
@Randolpho: "what's the big deal about hovering your mouse over the variable for a second and just seeing what type is it?" It adds time to the maintenance overhead... plus one second is only the hover time rather than counting the keyboard to mouse context switch. I don't know about you, but I work with a deadline. Every time I have to hover over a variable to find out what type it is, is time that I could have better spent fixing a problem.Illiberal
@R. Bemrose: If you're reading the code For The First Time (tm), you'll do a lot better with Right-Click->Go To Definition (F12, since you're apparently a keyboard jockey like me) than a mouse hover; you'll need to anyway if it's a custom type because you'll need to eventually analyze the type. But you don't need a type declaration for the method you're analyzing, since at that point you're more interested in how the type is used than what it actually is. And for 99.9% of the cases where the type is a core framework type, you can figure out what the type is by how it's used.Foulard
I'm with @Danko -- if you're naming variables variable, you've got bigger readability problems than whether or not the var keyword is appropriate. When an appropriate variable name is used, you rarely need to know the actual type to understand what the code does.Zareba
Your callback example is not valid C#.Halland
@Julian, thanks, I wrote it in a hurry, updated. But you could see the point as it wasWarrantable
H
36

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.

Harrisonharrod answered 19/5, 2010 at 13:47 Comment(1)
+1, only person to note that var has nothing to do with Variant.Donelson
R
27

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);
Ruiz answered 3/9, 2008 at 11:30 Comment(4)
(for info, you can get similar issues on anything where this is an implicit type conversion)Ruiz
Disagree with the part that you don't want to see it twice in the same line. It is possible that in the future you are not directly creating the variable after declaring (for example in an if below the definition) than it might not directly be clear what the type is. Most developers are used to see the type directly at the beginning of the line especially in complex code you don't want to make reading the code more difficult.Daltondaltonism
@TheVillageIdiot - I rolled back your edit, because on this occasion the hscroll is related to the point ;-pRuiz
@Daltondaltonism - my brain is limited; if it is complex, I don't want to see it twice and have to start comparing (interface/concrete/etc). I'm happy to see it once and think "typed as one of them".Ruiz
I
17

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.

Injure answered 3/9, 2008 at 11:30 Comment(3)
the type of 'something' is very clear to the compiler, internally, the "var" gets set to the return type of 'someMethod', it is clear to the compiler, but may not be clear to the developers working on the project. and Boo is growing on me quickly.Remorse
No, v = List<somethinglongtypename>(); is not even nicer. It is important to distinguish between introducing a new variable and assigning to an existing variable.Tamikatamiko
Well if you have assigned to 'v' before in the current scope, then it's assignment to an existing. Otherwise it's assignment to new variable 'v'. Easy.Injure
T
17

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.

Tomcat answered 3/9, 2008 at 11:30 Comment(4)
Why the heck are you code reviewing on paper? Think of the trees! ;)Melee
You can have the same problem without using var. The problem isn't var; the problem is bad variable names. If variable names are well-chosen, the use of var doesn't matter.Cellulose
I have a guy on my team that reviews his own code, and looks for bugs, by printing his code. His walls are COVERED with code. I once walked in and he had an entire large whiteboard covered with a single of his debugging exercises. It was probably ~10000 LOCToandfro
Variable names alone don't solve the problem unless you go back to hungarian notation where the type is part of the name.Unblushing
A
17

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.

Adept answered 19/5, 2010 at 13:51 Comment(0)
I
11

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>();
Inaccuracy answered 3/9, 2008 at 11:30 Comment(2)
I didn't actually consider this, at it seems from the other question that is a fairly strong point for one other time to use it.Cryology
That was basically the only reason they implemented it (besides being able to declare anonymous types, but they could have made "var" a special keyword that was only for anonymous types.)Dewayne
A
10

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

Armful answered 3/9, 2008 at 11:30 Comment(0)
S
10

Sure, int is easy, but when the variable's type is IEnumerable<MyStupidLongNamedGenericClass<int, string>>, var makes things much easier.

Spirituel answered 19/5, 2010 at 13:54 Comment(3)
+1 for this. int versus var is something to bicker about, but multiple nested generic types make var a godsend. This is where using the type name over and over really destroys the readability of code.Melena
This is absolutely the wrong reason for using it. If your code uses a nested generic type you should derive a specific named class for it. For example: class IntStringEnumerator : IEnumerable<MyStupidLongNamedGenericClass<int, string>> and then use the new name. That cleans up the code and describes the type better.Rosettarosette
Alright, but my example was just hyperbole. IntStringEnumerator i = new IntStringEnumerator() is still too much typing.Spirituel
B
9

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.

Bjork answered 3/9, 2008 at 11:30 Comment(2)
agreed - wondering why this nice side effect isn't being touted as much as some of the other, more subjective pros in the more popular responses.Ataxia
It hapen to me today. I have a factory class that return istance of a MainMenu class. Today i created a MainMenu2 with the same interface of MainMenu. I have my all app code untouched after the change!Lapidate
S
9

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.

Sacksen answered 3/9, 2008 at 11:30 Comment(1)
Your examples above aren't an argument for not using var; they're an argument for using good descriptive variable names. If, instead of [var fc = Factory.Run();] you had [bool fc = Factory.Run();], the code wouldn't become any clearer.Cellulose
Z
8

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?

Zetta answered 3/9, 2008 at 11:30 Comment(0)
K
8

@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.

Kelt answered 3/9, 2008 at 11:30 Comment(1)
It's interesting you say that because var can make refactoring simpler. If you've used var you don't have to. Now you can always rely on the IDE's refactoring tools, but you know, you can always rely on the IDE for the type as well :)Monostome
D
7

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.

Dewayne answered 3/9, 2008 at 11:30 Comment(3)
Presumably in .Net 4 where dynamic types are common place, this will become more important?Inaccuracy
On the contrary, if you're confused by "var" now, I would expect that you will be additionally confused by "dynamic." God forbid anyone ever declares a dynamic and then makes a reference to it using "var" :)Dewayne
I meant something like dynamic d = 52; var x = d; which ought to be fine.Dewayne
B
7

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;
Bistre answered 3/9, 2008 at 11:30 Comment(5)
Please rid off IQueriable<T> before iterating: anonEnumeration.ToList();Charmainecharmane
@DavidDiez could you rephrase? Your statement makes no sense. None of my code snippets reference IQueryable or .ToList()Bistre
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 }; does not return an IQueriable<T>?Charmainecharmane
@DavidDiez it depends on what AllPosts() returns - the asker refers to List<T> so I assumed that. In that case the result is that anonEnumeration will be of type IEnumerable<'a>. Now if AllPosts() returns IQueryable<T> instead then anonEnumeration will become IQueryable<'a> (note no i in Queryable) - however in that case my code still works because IQueryable<T> implements IEnumerable<T>. There are loads of better Q&As on here about the distinctions between them - here my case is that 'a is anonymous and var allows you to assign it to a statically typed variable.Bistre
Ohh I see, thanks for explaining it :) My comment was because iterating an IQueryable<T> is not a good practice because in each iteration you are making a read statement in DB. Be sure to *.ToList() IQueryable<T>'s before iterating themCharmainecharmane
I
7

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)

Inappreciable answered 19/5, 2010 at 14:9 Comment(1)
If the right hand side isn't clear enough to justify the use of var, then var isn't the problem: the right hand side is the problem. It's not descriptive enough. Customer c = GetContext() is still unclear and no better than using var.Halland
M
6

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.

Mawkish answered 3/9, 2008 at 11:30 Comment(2)
I find the repetition of stringBuilder sb = new StringBuilder() messy and longer to clearly recognise. It's extra noise. The problem is, determining what does and doesn't constitute extra intellectual effort to understand some code is pretty subjective!Cumquat
"var should never be used except where the type is not known..." - You can ALWAYS know the type, as does the compiler. This is not dynamic typing, it just lets the compiler determine the type for you. But the type is never an unknown.Lifeanddeath
H
6

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.

Herein answered 3/9, 2008 at 11:30 Comment(0)
S
6

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.

Seddon answered 3/9, 2008 at 11:30 Comment(2)
Wow. Ignoring all the arguments brought forth in this thread so far and re-setting the whole discussion is quite an achievement.Reside
This 100% describes how I feel about 'var', particularly from the standpoint of picking up someone elses code. Use of var radically changes the task at hand if it's littered throughout. +1Racialism
C
6

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.

Cellulose answered 3/9, 2008 at 11:30 Comment(2)
Funny you mention bilingualism as something that promotes the use of var. My antagonism towards the var keyword stems directly from my fluency in javascript! :)Rutledge
var in C# has no connection whatsoever with var in JavaScript. A var-declared variable in C# is strongly-typed.Cellulose
C
5

I used to think that the var keyword was a great invention but I put a a limit on it this was

  • Only use var where it is obvious what the type is immediately (no scrolling or looking at return types)

I came to realise this then gave me no benefit whatsoever and removed all var keywords from my code (unless they were specifically required), for now I think that they make the code less readable, especially to others reading your code.

It hides intent and in at least one instance lead to a runtime bug in some code because of assumption of type.

Catercorner answered 3/9, 2008 at 11:30 Comment(0)
D
5

In most cases, it's just simpler to type it - imagine

var sb = new StringBuilder();

instead of:

StringBuilder sb = new StringBuilder();

Sometimes it's required, for example: anonymous types, like.

var stuff = new { Name = "Me", Age = 20 };

I personally like using it, in spite of the fact that it makes the code less readable and maintainable.

Deposit answered 3/9, 2008 at 11:30 Comment(0)
E
5

None, except that you don't have to write the type name twice. http://msdn.microsoft.com/en-us/library/bb383973.aspx

Egotist answered 3/9, 2008 at 11:30 Comment(0)
O
5

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.

Orthopter answered 3/9, 2008 at 11:30 Comment(1)
Yup, compilers are smarter than us, get over it!Krug
S
5

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;

Sylvia answered 3/9, 2008 at 11:30 Comment(0)
H
4

With LINQ another very good reason to use var is that the compiler can optimize the query much more.

If you use a static list to store the result it will execute where you assign it to the list but with var it can potential merge the original query with later queries in the code to make more optimized queries to the database.

I had an example where I pulled some data in a first query and then looped over and requested more data to print out a table.

LINQ merges these so that the first only pulled the id.

Then in the loop it added an extra join I had not done there to fetch the data I had included in the original.

When tested this proved much more efficient.

Had we not used var it had made the queries exactly as we had written them.

Hyde answered 3/9, 2008 at 11:30 Comment(0)
G
3

var is like the dotted spaces in kids' books where kids have to fill it. Except in this case the Compiler will fill it with the right type which is usually written after the = sign.

Gorgonzola answered 3/9, 2008 at 11:30 Comment(8)
Wow, really? and no, you know what I'm talking about.Diametrically
Ok, you are the prof. and I am just a student. so I wont argue. But if you like you can ask MS to remoev the var keyword if it bothers you a lot. As you always say dear Andrew: "var must die".Gorgonzola
Thatls not at all what I'm talking about.Diametrically
Kinda backfired on ya, didn't it?Diametrically
Not really Andrew. My Rep. was 172 or so.. FYI, the downvote you give me was kinda unfair...Gorgonzola
let us continue this discussion in chatDiametrically
for the record, I was checking your answers and to be fair you know a lot. But you are arrogant.. so the formula is: (knowledge + arrogance) = 0 ;)Gorgonzola
Thanks for chatting with me and talking it all out!Diametrically
L
3

I'm fairly new in the C# world, after a decade as a Java professional. My initial thought was along the lines of "Oh no! There goes type safety down the drain". However, the more I read about var, the more I like it.

1) Var is every bit as type safe as an explicitly declared type would be. It's all about compile time syntactic sugar.

2) It follows the principle of DRY (don't repeat yourself). DRY is all about avoiding redundancies, and naming the type on both sides is certainly redundant. Avoinding redundancy is all about making your code easier to change.

3) As for knowing the exact type .. well .. I would argue that you always have a general idea is you have an integer, a socket, some UI control, or whatever. Intellisense will guide you from here. Knowing the exact type often does not matter. E.g. I would argue that 99% of the time you don't care if a given variable is a long or an int, a float or a double. For the last 1% of the cases, where it really matters, just hover the mouse pointer above the var keyword.

4) I've seen the ridiculous argument that now we would need to go back to 1980-style Hungarian warts in order to distinguish variable types. After all, this was the only way to tell the types of variables back in the days of Timothy Dalton playing James Bond. But this is 2010. We have learned to name our variables based upon their usage and their contents and let the IDE guide us as to their type. Just keep doing this and var will not hurt you.

To sum it up, var is not a big thing, but it is a really nice thing, and it is a thing that Java better copy soon. All arguments against seem to be based upon pre-IDE fallacies. I would not hesitate to use it, and I'm happy the R# helps me do so.

Lysozyme answered 3/9, 2008 at 11:30 Comment(0)
H
3

From the discussion on this topic, the outcome appears to be:

Good: var customers = new List<Customer>();

Controversial: var customers = dataAccess.GetCustomers();

Ignoring the misguided opinion that "var" magically helps with refactoring, the biggest issue for me is people's insistence that they don't care what the return type is, "so long as they can enumerate the collection".

Consider:

IList<Customer> customers = dataAccess.GetCustomers();

var dummyCustomer = new Customer();
customers.Add(dummyCustomer);

Now consider:

var customers = dataAccess.GetCustomers();

var dummyCustomer = new Customer();
customers.Add(dummyCustomer);

Now, go and refactor the data access class, so that GetCustomers returns IEnumerable<Customer>, and see what happens...

The problem here is that in the first example you're making your expectations of the GetCustomers method explicit - you're saying that you expect it to return something that behaves like a list. In the second example, this expectation is implicit, and not immediately obvious from the code.

It's interesting (to me) that a lot of pro-var arguments say "i don't care what type it returns", but go on to say "i just need to iterate over it...". (so it needs to implement the IEnumerable interface, implying the type does matter).

Higgins answered 3/9, 2008 at 11:30 Comment(0)
T
3

It's purely a convinience. The compiler will inferre the type (based on the type of the expression on the right hand side)

Tacho answered 3/9, 2008 at 11:30 Comment(0)
U
3

I use var whenever possible.

The actual type of the local variable shouldn't matter if your code is well written (i.e., good variable names, comments, clear structure etc.)

Undertrick answered 3/9, 2008 at 11:30 Comment(0)
K
3

Someone doesn't like criticism of var.. All answers downmodded.. oh well..

@Jon Limjap: I know. :) What I meant was that the readability is degraded like it is in VB6. I don't like to rely on Intellisense to figure out what type a given variable is. I want to be able to figure it out using the source alone.

Naming conventions doesn't help either - I already use good names. Are we going back to prefixing?

Kelt answered 3/9, 2008 at 11:30 Comment(0)
T
3

I had the same concern when I started to use var keyword.
However I got used to it over time and not going to go back to explicit variable types. Visual Studio's compiler\intellisense are doing a very good job on making work with implicitly typed variables much easier.

I think that following proper naming conventions can help you to understand code much better then explicit typing.

It seems to be same sort of questions like "shoud I use prefixes in variable names?".
Stick with good variable names and let the compiler think on variable types.

Tenure answered 3/9, 2008 at 11:30 Comment(0)
M
3

Well this one is pretty much gonna be opinionated all the way through, but I will try to give my view on it - albeit I think my view is so mixed up that you are probably not gonna get much out of it anyways.

First of all - there's anonymous types, for which you need to use the "var" keyword in order to assign an object with an anonymous type as its class - there's not much discussion here, "var" is needed.

For simpler types however, ints, longs, strings - so forth - I tend to put in the proper types. Mainly because it is a bit of a "lazy man's tool" and I don't see much gain here, very few keystrokes and the possible confusion it could provide later down the road just ain't worth it. Especially the various types for floating point numbers (float, double, decimal) confuse me as I am not firm with the postfixes in the literals - I like to see the type in the source code.

With that said, I tend to use var alot if the type is more complex and/or it is explicitly repeated on the righthand-side of the assignment. This could be a List<string> or etc, such as:

var list = new List<string>();

In a such case, I see no use to repeat the type twice - and especially as you start changing your code and the types change - the generic types might get more and more complicated and as such having to change them twice is just a pain. However of course if you wish to code against an IList<string> then you have to name the type explicitly.

So in short I do the following:

  • Name the type explicitly when the type is short or cannot be read out of context
  • Use var when it has to be used (duh)
  • Use var to be lazy when it (in my mind) does not hurt readability
Malmo answered 19/5, 2010 at 13:53 Comment(0)
W
2

Amazed this hasn't been noted so far, but it is common sense to use var for foreach loop variables.

If you specify a specific type instead, you risk having a runtime cast silently inserted into your program by the compiler!

foreach (Derived d in listOfBase)
{

The above will compile. But the compiler inserts a downcast from Base to Derived. So if anything on the list is not a Derived at runtime, there is an invalid cast exception. Type safety is compromised. Invisible casts are horrible.

The only way to rule this out is to use var, so the compiler determines the type of the loop variable from the static type of the list.

Willhite answered 3/9, 2008 at 11:30 Comment(0)
R
2

There is bound to be disagreement near the edge cases, but I can tell you my personal guidelines.

I look at these the criteria when I decide to use var:

  • The type of the variable is obvious [to a human] from the context
  • The exact type of the variable is not particularly relevant [to a human]
    [e.g. you can figure out what the algorithm is doing without caring about what kind of container you are using]
  • The type name is very long and interrupts the readability of the code (hint: usually a generic)

Conversely, these situations would push me to not use var:

  • The type name is relatively short and easy to read (hint: usually not a generic)
  • The type is not obvious from the initializer's name
  • The exact type is very important to understand the code/algorithm
  • On class hierarchies, when a human can't easily tell which level of the hierarchy is being used

Finally, I would never use var for native value types or corresponding nullable<> types (int, decimal, string, decimal?, ...). There is an implicit assumption that if you use var, there must be "a reason".

These are all guidelines. You should also think also about the experience and skills of your coworkers, the complexity of the algorithm, the longevity/scope of the variable, etc, etc.

Most of the time, there is no perfect right answer. Or, it doesn't really matter.

[Edit: removed a duplicate bullet]

Reneerenegade answered 3/9, 2008 at 11:30 Comment(0)
M
2

Static typing is about contracts, not source code. The idea there is a need to have the static information on a single line of what "should" be a small method. Common guidelines recommend rarely exceeding 25 lines per method.

If a method is large enough that you can't keep track of a single variable within that method, you are doing something else wrong that would make any criticism of var pale in comparison.

Actually, one of the great arguments for var is that it can make refactoring simpler because you no longer have to worry that you made your declaration overly restrictive (i.e. you used List<> when you should have used IList<>, or IEnumerable<>). You still want to think about the new methods signature, but at least you won't have to go back and change your declarations to match.

Mayst answered 3/9, 2008 at 11:30 Comment(0)
K
2

After just converting over to the 3.0 and 3.5 frameworks I learned about this keyword and decided to give it a whirl. Before committing any code I had the realization that it seemed backwards, as in going back toward an ASP syntax. So I decided to poke the higher ups to see what they thought.

They said go ahead so I use it.

With that said I avoid using it where the type requires some investigation, like this:

var a = company.GetRecords();

Now it could just be a personal thing but I immediately cant look at that and determine if its a collection of Record objects or a string array representing the name of records. Whichever the case I believe explicit declaration is useful in such an instance.

Kerriekerrigan answered 3/9, 2008 at 11:30 Comment(2)
You're arguing against var on the basis of bad variable and method names. Would var still be so bad if your example used good variable and method names?Cellulose
Not necessarily. So long as when I am going through the code I know immediately what type the variable is without having to check the method assigning it, I'm all for it.Kerriekerrigan
R
2

I think you may be misunderstanding the usage of var in C#. It is still strong typing, unlike the VB varient type so there is no performance hit from using it or not.

Since there is no effect on the final compiled code it really is a stylist choice. Personally I don't use it since I find the code easier to read with the full types defined, but I can imagine a couple of years down the line that full type declaration will be looked at in the same way as Hungarian notation is now - extra typing for no real benefit over the information that intellisense gives us by default.

Ralph answered 19/5, 2010 at 13:50 Comment(0)
G
2

I think you point out the main problem with var in your question: "I don't have to figure out the type". As other have pointed out, there is a place for var, but if you don't know the type you're dealing with, there's a pretty good chance that you're going to have problems down the road - not in all cases, but there's enough of a smell there so that you should be suspicious.

Gratitude answered 19/5, 2010 at 13:52 Comment(0)
C
2

Apart from readability concerns, there is one real issue with the use of 'var'. When used to define variables that are assigned to later in the code it can lead to broken code if the type of the expression used to initialize the variable changes to a narrower type. Normally it would be safe to refactor a method to return a narrower type than it did before: e.g. to replace a return type of 'Object' with some class 'Foo'. But if there is a variable whose type is inferred based on the method, then changing the return type will mean that this variable can longer be assigned a non-Foo object:

var x = getFoo(); // Originally declared to return Object
x = getNonFoo();

So in this example, changing the return type of getFoo would make the assignment from getNonFoo illegal.

This is not such a big deal if getFoo and all of its uses are in the same project, but if getFoo is in a library for use by external projects you can no longer be sure that narrowing the return type will not break some users code if they use 'var' like this.

It was for exactly this reason that when we added a similar type inferencing feature to the Curl programming language (called 'def' in Curl) that we prevent assignments to variables defined using this syntax.

Carnatic answered 19/5, 2010 at 14:21 Comment(0)
M
2

var is a placeholder introduced for the anonymous types in C# 3.0 and LINQ.

As such, it allows writing LINQ queries for a fewer amount of columns within, let's say, a collection. No need to duplicate the information in memory, only load what's necessary to accomplish what you need to be done.

The use of var is not bad at all, as it is actually not a type, but as mentioned elsewhere, a placeholder for the type which is and has to be defined on the right-hand side of the equation. Then, the compiler will replace the keyword with the type itself.

It is particularly useful when, even with IntelliSense, the name of a type is long to type. Just write var, and instantiate it. The other programmers who will read your code afterward will easily understand what you're doing.

It's like using

public object SomeObject { get; set; }

instead of:

public object SomeObject {
    get {
        return _someObject;
    } 
    set {
        _someObject = value;
    }
}
private object _someObject;

Everyone knows what's the property's doing, as everyone knows what the var keyword is doing, and either examples tend to ease readability by making it lighter, and make it more pleasant for the programmer to write effective code.

Mizell answered 19/5, 2010 at 15:20 Comment(0)
D
1

what most are ignoring:

var something = new StringBuilder(); 

isn't normally typed as fast as

StringBuilder something = KEY'TAB'();
Dorisdorisa answered 3/9, 2008 at 11:30 Comment(2)
Yeah, but you duplicate "StringBuilder". Having it twice makes for more code. I like var because it makes code shorter, less information, easier to read.Chesser
...and more like Javascript. var was intended for LINQ, abusing it should be punished by removing intellisense from your Visual Studio for a week.Escalante
G
1

One good argument why vars should not be used as a mere "typing shortcut", but should instead be used for scenarios they were primarily designed for: Resharper (at least v4.5) cannot find usages of a type if it is represented as a var. This can be a real problem when refactoring or analyzing the source code.

Garthgartner answered 3/9, 2008 at 11:30 Comment(0)
H
1

Sometimes the compiler can also infer what is required "better" than the developer - at least a developer who does not understand what the api he's using requires.

For example - when using linq:

Example 1

Func<Person, bool> predicate = (i) => i.Id < 10;
IEnumerable<Person> result = table.Where(predicate);

Example 2

var predicate = (Person i) => i.Id < 10;
var result = table.Where(predicate);

In the above code - assuming one is using Linq to Nhibernate or Linq to SQL, Example 1 will bring the entire resultset for Person objects back and then do filter on the client end. Example 2 however will do the query on the server (such as on Sql Server with SQL) as the compiler is smart enough to work out that the Where function should take a Expression> rather than a Func.

The result in Example 1 will also not be further queryable on the server as an IEnumerable is returned, while in Example 2 the compiler can work out if the result should rather be a IQueryable instead of IEnumerable

Hierarchy answered 3/9, 2008 at 11:30 Comment(0)
I
1

You can let the compiler (and the fellow who maintains the code next) infer the type from the right hand side of the initializer assignment. If this inference is possible, the compiler can do it so it saves some typing on your part.

If the inference is easy for that poor fellow, then you haven't hurt anything. If the inference is hard, you've made the code harder to maintain and so as a general rule I wouldn't do it.

Lastly, if you intended the type to be something particular, and your initializer expression actually has a different type, using var means it will be harder for you to find the induced bug. By explicitly telling the compiler what you intend the type to be, when the type isn't that, you would get an immediate diagnostic. By sluffing on the type declaration and using "var", you won't get an error on the initialization; instead, you'll get a type error in some expression that uses the identifier assigned by the var expression, and it will be harder to understand why.

So the moral is, use var sparingly; you generally aren't doing yourself or your downstream fellow maintainer a lot of good. And hope he reasons the same way, so you aren't stuck guessing his intentions because he thought using var was easy. Optimizing on how much you type is a mistake when coding a system with a long life.

Imply answered 3/9, 2008 at 11:30 Comment(0)
K
1

Arriving a bit late at this discussion, but I'd just like to add a thought.

To all those who are against type inference (because that's what we're really talking about here), what about lambda expressions? If you insist on always declaring types explicitly (except for anonymous types), what do you do with lambdas? How does the "Don't make me use mouseover" argument apply to var but not to lambdas?

UPDATE

I've just thought of one argument against 'var' which I don't think anyone has mentioned yet, which is that it 'breaks' "Find all references", which could mean (for example) that if you were checking out usage of a class before refactoring, you would miss all the place where the class was used via var.

Krug answered 3/9, 2008 at 11:30 Comment(2)
Wonder how many of the pro-var people have been 'polluted' by F#? :)Krug
It's true. I often find myself wishing the C# type inference was as good as that in F#.Pandurate
S
1

I think people do not understand the var keyword. They confuse it with the Visual Basic / JavaScript keyword, which is a different beast all toghether.

Many people think the var keyword implies weak typing (or dynamic typing), while in fact c# is and remains strongly typed.

If you consider this in javascript:

var something = 5;

you are allowed to:

something = "hello";

In the case of c#, the compiler would infer the type from the first statement, causing something to be of type "int", so the second statement would result in an exception.

People simply need to understand that using the var keyword does not imply dynamic typing and then decide how far they want to take the use of the var keyword, knowing it will have absolutely no difference as to what will be compiled.

Sure the var keyword was introduced to support anonymous types, but if you look at this:

LedDeviceController controller = new LedDeviceController("172.17.0.1");

It's very very verbose, and I'm sure this is just as readable, if not more:

var controller = new LedDeviceController("172.17.0.1");

The result is exactly the same, so yes I use it throughout my code

UPDATE:

Maybe, just maybe... they should have used another keyword, then we would not be having this discussion... perhaps the "infered" keyword instead of "var"

Streamlined answered 3/9, 2008 at 11:30 Comment(0)
S
1

I find that using the var keyword actually makes the code more readable because you just get used to skipping the 'var' keyword. You don't need to keep scrolling right to figure out what the code is doing when you really don't care about what the specific type is. If I really need to know what type 'item' is below, I just hover my mouse over it and Visual Studio will tell me. In other words, I would much rather read

foreach( var item in list ) { DoWork( item ); }

over and over than

foreach( KeyValuePair<string, double> entry in list ) { DoWork( Item ); }

when I am trying to digest the code. I think it boils down to personal preference to some extent. I would rely on common sense on this one -- save enforcing standards for the important stuff (security, database use, logging, etc.)

-Alan.

Scissure answered 3/9, 2008 at 11:30 Comment(0)
C
1

I don't understand why people start debates like this. It really serves no purpose than to start flame wars at then end of which nothing is gained. Now if the C# team was trying to phase out one style in favor of the other, I can see the reason to argue over the merits of each style. But since both are going to remain in the language, why not use the one you prefer and let everybody do the same. It's like the use of everybody's favorite ternary operator: some like it and some don't. At the end of the day, it makes no difference to the compiler.

This is like arguing with your siblings over which is your favorite parent: it doesn't matter unless they are divorcing!

Corporation answered 3/9, 2008 at 11:30 Comment(0)
B
1

kronoz - in that case (overloads for both) would it matter? If you have two overloads that took the different types you would essentially be saying that either can be passed and do the same thing.

You shouldn't have two overloads that do completely different actions depending on the types passed.

While you might get some confusion in that instance it would still be entirely type safe, you'd just have someone calling the wrong method.

Bistre answered 3/9, 2008 at 11:30 Comment(0)
A
1

I have to agree with Matt Hamilton.

Var can make your code much more readable and understandable when used with good variable names. But var can also make your code as impossible to read and understand as Perl when used badly.

A list of good and bad uses of var isn't really going to help much either. This is a case for common sense. The larger question is one of readability vs. write-ability. Lots of devs don't care if their code is readable. They just don't want to type as much. Personally I'm a read > write guy.

Antigorite answered 3/9, 2008 at 11:30 Comment(0)
I
1

I use var in the following situations:

  1. When I have to (result is anonymous)
  2. When the type is on the same line as the code, e.g.

    var emp = new Employee();

Its obvious we want an Employee (because we're creating a new Employee object), so how is

Employee emp = new Employee() any more obvious?

I do NOT use var when the type cannot be inferred, e.g.

var emp = GetEmployee();

Because the return type is not immediately obvious (is at an Employee, an IEmployee, something that has nothing to do with an Employee object at all, etc?).

Iconolatry answered 3/9, 2008 at 11:30 Comment(5)
Everyone opposed to var says this. But why do you need to know whether it's an Employee or an IEmployee? What practical difference will it make to what you're doing?Cellulose
"I do NOT use var when the type cannot be inferred" - Um, you CANNOT use var when the type cannot be inferred, since var depends on type inference. In your example, the type CAN be inferred.Pandurate
@Joel Mueller I meant inferred by a human, not by the parser. I thought that was clear by the following sentence.Iconolatry
Well, if the return type is nothing to do with an employee object at all, then calling the method GetEmployee was probably a bad decision. The circumstances where a human needs to know specifically if it's an Employee or an IEmployee in less time than it takes to mouse over the variable are pretty limited, in my opinion. I think a human can infer with a fairly high degree of confidence what they need to know, even if they use var. Not that you have to agree with me, of course, I just don't think it's a very good argument against using var.Pandurate
You're right about IEmployee vs Employee. However, my personal opinion is that not having the actual type right on the screen goes against the spirit of a strongly typed language like c# (just a gut feeling... nothing quantifiable). Do I freak out when someone does var e = GetEmployee()? Not at all. In fact I've probably done it a bunch of times myself.Iconolatry
T
1

@erlando, out of curiosity, why do you need to know the variable's type looking at the source code?

In my practice I found that variable type is matter for me only at the time I'm using it in the code.

If I'm trying to do some inappropriate operation on someVar compiler gladly gives me an error\warning.

I really don't care what type someVar has if I understand why it's being used it the given context.

Tenure answered 3/9, 2008 at 11:30 Comment(0)
T
1

In our office, our CTO has categorically banned the use of the var keyword, for the same reasons that you have stated.

Personally I find the use of var only valid in new object declarations, since the type of the object is obvious in the statement itself.

For LINQ queries, you can resolve results to:

IEnumerable<TypeReturnedBySelectObject>
Tomcat answered 3/9, 2008 at 11:30 Comment(3)
That must be a new use of the word "awesome".Oni
In that case your CTO should also ban the use of LINQ, but honestly I think he should try and understand the var keyword in c# and how it has nothing to do with the var keyword in VB or JavaScript... Maybe they should have simply chosen another keyword for thisStreamlined
You can't always resolve results to IEnumerable<SomeSpecificType> in LINQ queries. If you're selecting specific fields, you'll end up with an anonymous type, and you'll have to use var.Cellulose
D
1

Deleted for reasons of redundancy.

vars are still initialized as the correct variable type - the compiler just infers it from the context. As you alluded to, var enables us to store references to anonymous class instances - but it also makes it easier to change your code. For example:

// If you change ItemLibrary to use int, you need to update this call
byte totalItemCount = ItemLibrary.GetItemCount();

// If GetItemCount changes, I don't have to update this statement.
var totalItemCount = ItemLibrary.GetItemCount();

Yes, if it's hard to determine a variable's type from its name and usage, by all means explicitly declare its type.

Dormancy answered 19/5, 2010 at 13:48 Comment(0)
G
1

In my opinion, there is no problem in using var heavily. It is not a type of its own (you are still using static typing). Instead it's just a time saver, letting the compiler figure out what to do.

Like any other time saver (such as auto properties for example), it is a good idea to understand what it is and how it works before using it everywhere.

Goshorn answered 19/5, 2010 at 13:49 Comment(0)
F
1

var is not bad. Remember this. var is not bad. Repeat it. var is not bad. Remember this. var is not bad. Repeat it.

If the compiler is smart enough to figure out the type from the context, then so are you. You don't have to have it written down right there at declaration. And intellisense makes that even less necessary.

var is not bad. Remember this. var is not bad. Repeat it. var is not bad. Remember this. var is not bad. Repeat it.

Foulard answered 19/5, 2010 at 13:51 Comment(6)
So, are you saying var is not bad? ;-)Erudition
@WaggingSiberian: What I'm saying is var is not bad. Remember this. var is not bad. Repeat it.Foulard
@Randolpho: I think I got it. Var is not bad! I will learn to love var! I can do it.Erudition
@WaggingSiberian: Yes, you can! :)Foulard
"He had won the victory over himself. He loved var." (forgive any misquotation.)Superaltar
Ouch, I just got mugged. Three downvotes in as many minutes. I guess some people really get up in arms about var. Must be former Java developers....Foulard
S
1

If you know the type, use the type. If you don't know the type, why not? If you can't know the type, that's okay -- you've found the only valid use.

And I'm sorry, but if the best you can do is "it makes the code all line up", that's not a good answer. Find a different way to format your code.

Sweepings answered 19/5, 2010 at 16:27 Comment(0)
A
0

Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

// z is compiled as an int

var z = 100;

// s is compiled as a string below

var s = "Hello";

// a is compiled as int[]

var a = new[] { 0, 1, 2 };

// expr is compiled as IEnumerable // or perhaps IQueryable

var expr =
    from c in customers
    where c.City == "London"
    select c;

// anon is compiled as an anonymous type

var anon = new { Name = "Terry", Age = 34 };

// list is compiled as List

var list = new List<int>();

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.

Antitank answered 3/9, 2008 at 11:30 Comment(0)
T
0

var is the way to deal with anonymous types, whether from LINQ statements or not. Any other use is heavily dependent on who will read your code and what guidelines are in place.

If you are the only audience or your audience is comfortable with using var or is very familiar with your code then I guess it doesn't matter. If you use it like: var s = new SqlConnection() then it largely doesnt matter and probably improves code readability. If people aren't too picky and its okay for them to do a little work to know the type when its not apparent (which is not needed in most cases, how you use it in the following statements would usually explain everything) then its alright.

But if you have picky, close-minded teammates who love to whine or if your company's design guidelines specifically forbid using var when the type is not obvious then you will most likely meet heavy opposition.

If using var makes your code insanely difficult to read, you will probably get shot by using var even if its probably your app design that is to blame.

If var introduces ambiguity (sort of like your IEnumerable/IEnumerable example), just don't use it and be explicit. But var does have its conveniences and in some cases, IMHO, even improves readabilty by reducing clutter.

Trulatrull answered 3/9, 2008 at 11:30 Comment(0)
H
0

"The only thing you can really say about my taste is that it is old fashioned, and in time yours will be too." -Tolkien.

Hefner answered 3/9, 2008 at 11:30 Comment(0)
B
0

You don't have to write out the type name and no this is not less performant as the type is resolved at compile time.

Bookbinding answered 3/9, 2008 at 11:30 Comment(0)
K
0

From Essential LINQ:

It is best not to explicitly declare the type of a range variable unless absolutely necessary. For instance, the following code compiles cleanly, but the type could have been inferred by the compiler without a formal declaration:

List<string> list = new List<string> { "LINQ", "query", "adventure" };
var query = from string word in list
      where word.Contains("r")
      orderby word ascending
      select word;

Explicitly declaring the type of a range variable forces a behind-the-scenes call to the LINQ Cast operator. This call may have unintended consequences and may hurt performance. If you encounter performance problems with a LINQ query, a cast like the one shown here is one possible place to begin looking for the culprit. (The one exception to this rule is when you are working with a nongeneric Enumerable, in which case you should use the cast.)

Kovacs answered 3/9, 2008 at 11:30 Comment(0)
K
0

I don't think var per say is a terrible language feature, as I use it daily with code like what Jeff Yates described. Actually, almost everytime I use var is because generics can make for some extremely wordy code. I live verbose code but generics take it a step too far.

That said, I (obviously... ) think var is ripe for abuse. If code gets to 20+ lines in a method with vars littered through out, you will quickly make maintenance a nightmare. Additionally, var in a tutorial is incredibly counter intuitive and generally is a giant no-no in my books.

On the flipside, var is an "easy" feature that new programmers are going to latch onto and love. Then, within a few minutes/hours/days hit a massive roadblock when they start hitting the limits. "Why can't I return var from functions?" That kind of question. Also, adding a pseudo dynamic type to a strongly typed language is something that can easily trip up a new developer. In the long run, I think the var keyword will actually make c# harder to learn for new programmers.

That said, as an experienced programmer I do use var, mostly when dealing with generics ( and obviously anonymous types ). I do hold by my quote, I do believe var will be one of the worst abused c# features.

Kharkov answered 3/9, 2008 at 11:30 Comment(1)
The phrase is "per se." It's Latin for "by itself." I do agree that var should be used sparingly if at all in tutorials or example code - but only because such code is typically not read in an IDE.Pandurate
S
0

var is great when you don't want to repeat yourself. For example, I needed a data structure yesterday that was similar to this. Which representation do you prefer?

Dictionary<string, Dictionary<string, List<MyNewType>>> collection = new Dictionary<string, Dictionary<string, List<MyNewType>>>();

or

var collection = new Dictionary<string, Dictionary<string, List<MyNewType>>>();

Note that there is little ambiguity introduced by using var in this example. However, there are times when it wouldn't be such a good idea. For example, if I used var as in the following,

var value= 5;

when I could just write the real type and remove any ambiguity in how 5 should be represented.

double value = 5;
Surname answered 3/9, 2008 at 11:30 Comment(6)
Note, the first value has no ambiguity, all the numerical types have their own litteral syntax. 5 for an int, 5LU for unsigned long, 5m for decimal, ...Orthopter
@Richard: No compiler ambiguity - but not so good for maintenance.Surname
@Jeff: just expanded my answer on that topic. Learning some F# has really changed my view...Orthopter
Using double instead of var in your example doesn't "remove ambiguity"; it changes the code. [var value = 5;] makes value an int, not a double. But you could also do [var value = 5.0;] to make it a double.Cellulose
@Kyralessa: yes, fundamentally speaking, it does. However, regardless, the point I was making is still valid.Surname
And in fact, you point out where the error is in using var here. You lose intention and possibly, that can lead to problems (such as getting int instead of double).Surname
C
0

It can make code simpler and shorter, especially with complicated generic types and delegates.

Also, it makes variable types easier to change.

Cortex answered 3/9, 2008 at 11:30 Comment(0)
U
0

Depends, somehow it makes the code look 'cleaner', but agree it makes it more unreadable to...

Uncharted answered 3/9, 2008 at 11:30 Comment(0)
D
0

VS2008 w/resharper 4.1 has correct typing in the tooltip when you hover over "var" so I think it should be able to find this when you look for all usages of a class.

Haven't yet tested that it does that yet though.

Demilune answered 3/9, 2008 at 11:30 Comment(0)
E
0

I don't use var as it goes against the roots of C# - C/C++/Java. Even though it's a compiler trick it makes the language feel like it's less strongly typed. Maybe 20+ years of C have engrained it all into our (the anti-var people's) heads that we should have the type on both the left and right side of the equals.

Having said that I can see its merits for long generic collection definitions and long class names like the codinghorror.com example, but elsewhere such as string/int/bool I really can't see the point. Particularly

foreach (var s in stringArray)
{

}

a saving of 3 characters!

The main annoyance for me is not being able to see the type that the var represents for method calls, unless you hover over the method or F12 it.

Escalante answered 3/9, 2008 at 11:30 Comment(3)
Heh. If C++/Java/etc. are your idea of what a strongly/statically typed language should be like, then you've never used a language with a real static type system--many of which have far more type inference than C# and far stronger type guarantees than the languages you mention. This reaction to var is cargo cult programming, pure and simple.Mocha
@C.A.McCann are you saying types are cargo cult programming? I'm confused. var was introduced into C# in 3.0 alongside LINQ which was arguably its main purpose, there was a good 5 years of C# development I (and other moaners like me) did without it.Escalante
Static types are great, having to write out types for every declaration is mostly useless. Type inference has been around for longer than C# itself has, in languages that have real static types, not the crippled garbage you get in C-style languages.Mocha
D
0

var is essential for anonymous types (as pointed out in one of the previous responses to this question).

I would categorise all other discussion of its pros and cons as "religious war". By that I mean that a comparison and discussion of the relative merits of...

var i = 5;
int j = 5;

SomeType someType = new SomeType();
var someType = new SomeType();

...is entirely subjective.

Implicit typing means that there is no runtime penalty for any variable being declared using the var keyword, so it comes down to being a debate about what makes the developers happy.

Dereliction answered 3/9, 2008 at 11:30 Comment(0)
V
0

@Keith -

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.

That isn't quite true - if a method is overloaded to both IEnumerable<int> and IEnumerable<double> then it may silently pass the unexpected inferred type (due to some other change in the program) to the wrong overload hence causing incorrect behaviour.

I suppose the question is how likely it is that this sort of situation will come up!

I guess part of the problem is how much confusion var adds to a given declaration - if it's not clear what type something is (despite being strongly typed and the compiler understanding entirely what type it is) someone might gloss over a type safety error, or at least take longer to understand a piece of code.

Variation answered 3/9, 2008 at 11:30 Comment(0)
T
0

@erlando,

Talking about refactoring it seems to be much easier to change variable type by assigning instance of new type to one variable rather then changing it in multiple places, isn't it ?

As for code review I see no big issues with var keyword. During code review I prefer to check code logic rather variable types. Of course there might be scenarios where developer can use inappropriate type but I think that number of such cases is so small it wouldn't be a reason for my to stop using var keyword.

So I repeat my question. Why does variable type matter to you?

Tenure answered 3/9, 2008 at 11:30 Comment(0)
A
0

First.

var is not a type and not some special feature (like c# 4.0 dynamic). It is just a syntax sugar. You ask compiler to infer the type by the right hand side expression. The only necessary place is anonymous types.

I don't think that using var is neither good or evil, it is coding style. Personally i don't use it, but i don't mind using it by other team members.

Aleris answered 19/5, 2010 at 13:52 Comment(3)
@Foulard - WTF? i don't read Slashdot at all, so your analogy is not clear to me. but what i definitely know that SO is not Literature Club, and downvoting because you don't like my writing style is not very clever.Aleris
@Foulard - first was name of paragraph. i wanted to write Second but forgot about it.Aleris
It was a tongue in cheek downvote, done for kicks. I'll go randomly upvote one of your other posts just to offset your rep loss. Deal?Foulard
G
0

Eric's answer here...

Namespace scoped aliases for generic types in C#

is related.

Part of the issue is that there is no strongly typed aliasing in C#. So many developers use var as a partial surrogate.

Gaillardia answered 19/5, 2010 at 14:51 Comment(0)
S
0

It's not wrong, but it can be inappropriate. See all the other responses for examples.

var x = 5; (bad)

var x = new SuperDooperClass(); (good)

var x = from t in db.Something select new { Property1 = t.Field12 }; (better)

Sterculiaceous answered 19/5, 2010 at 15:9 Comment(0)
P
0

var is good as it follows the classic DRY rule, and it is especially elegant when you indicate the type in the same line as declaring the variable. (e.g. var city = new City())

Plunk answered 19/5, 2010 at 16:3 Comment(0)
C
-1

Don't use that, makes your code unreadable.

ALWAYS use as strict typing as possible, crutches only makes your life hell.

Congregate answered 19/5, 2010 at 15:5 Comment(2)
var is strict typing. It’s not a crutch in any sense. And it doesn’t make the code unreadable.Reside
it actually improves readability in some cases: using (var con = new SqlConnection()) is easier on the eyes than having to type the type twiceTrulatrull
T
-5

If you are lazy and use var for anything other than anonymous types, you should be required to use Hungarian notation in the naming of such variables.

var iCounter = 0;

lives!

Boy, do I miss VB.

Trapes answered 3/9, 2008 at 11:30 Comment(4)
-1: Digging out old question just to flame agains type interference, without reason - not even a subjective or arguably stupid reason, just no reason at all. The fact that you call this abomination Hungarian notation (I don't care some calls it so, in my book Hungarian notation still means incorporating the variable's purpose in the name, not its exact type) only makes it feel more appropriate.Eros
Sorry you feel that way. In my experience, Hungarian notation has always meant the type of the variable is the prefix; the part of the name after the type prefix describes the purpose of the variable. You think Hungarian notation means you prefix and suffix the name with its purpose? Now there's some of that redundancy that has been brought up in this thread! Hungarian notation has always been about using prefixes to give the reader of the code an idea of the type of the variable. And this is something that those who use var need to do! Using var for non-anon types is indeed an "interference."Trapes
Type inference that is, of course - silly typo. But you still don't give anything like a reason why type interference is a bad thing™. Concerning Hungarian: Ask Wikipedia. It has a nice example somewhere, the prefix i: You'd use it a "integer", while the "apps Hungarian notation", as wiki calls it, uses it for "index" - the latter contains much more semantic information and actually tells you something the type system can't tell you, while the first is redunant with a halfway decent IDE.Eros
Good point. I should have used "var intCounter = 0;" in my example (sorry, I haven't used VB in quite a while). But the type of Hungarian I was referring to should have been obvious from the VB context. Perhaps my use of sarcasm to get across my point of why using a var for anything other that anon types did not translate well (although "lazy" is certainly an explicit reason). And if you don't understand why I think it is pure laziness to use var for anything but anon types, well, just read some of the other replies to this thread. And remember, not everyone uses (or has) an IDE.Trapes

© 2022 - 2024 — McMap. All rights reserved.