This question already has answers here:
Why would var be a bad thing?
(18 answers)
Closed 8 years ago.
I just installed a trial version of ReSharper and one of the first things I noticed is that it always suggests to replace explicitly typed local variables with implicitly typed ones, e.g:
public string SomeMethod(int aParam)
{
int aNumber = SomeOtherMethod(aParam);
// should be changed to:
var aNumber = SomeOtherMethod(aParam);
}
I think explicitly typed variables are more readable (more explicit).
What do you think about ReSharper's suggestion? Is there any advantage in using implicitly typed variables? When do you use implicit/explict vars?
I personally only use “var” when I can clearly distinguish the variable Type by just reading the declaration, for example:
var someVariable = new List<int>();
In the example above, its evident that “var” refers to “List<int>”.
I don’t like to use “var” when I have to go to some method definition to find out what variable type “var” represents or by having to rely on visual studio intelli-popup or whatever that is called, for example this in not ok to me:
var someVaraible = SomeMethod();
I mean, what is the “SomeMethod” function supposed to return? Can you tell just by looking at the line of code? No you can’t, so that is why I avoid using “var” on those situations.
There's a lot of discussion about this, but I think it all comes down to personal taste, just like using the 'this' keyword almost everywhere.
I personally prefer explictly typed variables, but when using nested generic collections things can become more readable using an implicitly typed variable. Look at:
Dictionary<string, Dictionary<string, string>> myDictionary = new Dictionary<string, Dictionary<string, string>>();
vs:
var myDictionary = new Dictionary<string, Dictionary<string, string>>();
EDIT: this SO topic covers the same topic, with some nice replies: What to use: var or object name type?
EDIT2: Working a lot with async nowadays, I find that using explicity typed variables can sometimes prevent nasty bugs. Consider this silly example where you would want to return the Id of a user. Also consider that GetUserAsync returns a Task<User>. If you use implicitly typed variables, you would end up using something like this:
public long GetUserId()
{
var user = GetUserAsync();
return user.Id;
}
This compiles, but it is wrong. 'user' is actually a Task<User>. And it compiles as Task also has an Id property. In this case, one would accidentally return the Id of a Task instead of the User.
public long GetUserId()
{
User user = GetUserAsync();
return user.Id;
}
The above does not compile, as the compiler will complain that you cannot cast a Task to a User. Adding the await keyword of course solves this.
I've actually had this happen to me once :-)
Just in case some haven’t noticed yet, you can easily change the “suggestions” in Reshaper (Reshaper -> Options -> Languages -> Context Actions -> “Replace explicit type specification with ‘var’”).
I personally prefer to have explicit type specifications everywhere, but I'm not too fussy about it.
It's just easier to type the var pseudo-keyword at times than a huge type name, especially if a generic could be involved. However, you should know they're functionally identical. There's no performance difference or anything either way. The compiler derives the type of the right-side of the assignment and replaces var with that type. It's not happening at run-time like a VB variant.
FWIW, the var keyword is plainly readable in many cases. Especially if...
The right-side of the assignment is a constructor expression.
var map = new Dictionary>();
Local variables have good names.
HTH
Related
I ran into a problem while doing my job, which is porting software from flash AS3 to .NET/Mono. In AS3 code base I can find many Object declarations that are initialized like this:
private const MAPPING:Object =
{
ssdungf:'flydung',
ssdungt:'flydung',
superfutter:'superfeed'
}
The best option for me would be in C# using anonymous type like this:
var MAPPING = new
{
ssdungf = "flydung",
ssdungt = "flydung",
superfutter = "superfeed"
};
The problem is... well let me quote MSDN (source):
You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type
But they don't say why.
So the question remains: why you cannot declare a field and property as having an anonymous type? Why .NET creators stripped it from that option?
I am getting warning here from SO that my question appears subjective, but I think it is not at all - there need to be objective reason for that.
As for me, I don't see any obstacles for that but somehow it is not supported. As compiler can easily generate the type for field or property of class, in a same manner as it does for local variables.
The option for me was to use dynamic type but unfortunately Mono engine I am using is stripped from that.
Also the option for me is to use object type and using later reflection to find these fields:
private static readonly object MAPPING = new
{
ssdungf = "flydung",
ssdungt = "flydung",
superfutter = "superfeed"
};
But using reflection is this situation is dirty I would say.
I tried to find answer, but I really didn't find any. Here are some SO answers to similar questions, but they don't answer why:
Can a class property/field be of anonymous type in C# 4.0?
Declaring a LIST variable of an anonymous type in C#
How do you declare a Func with an anonymous return type?
Why you cannot declare a field and property as having an anonymous type?
Because C# is statically typed, so any memory location has to be given a type, and declaration does so. With locals we can infer from context if its initialised at the same time as declaration with var but that is a shorthand for a type that is usable even when the type hasn't got a name.
What would a field with an anonymous type, that is to say a statically-bound but indescribable type, mean?
dynamic would indeed be the closest analogy to the code you are porting, but since that isn't available to you, you might consider using an IDictionary<string, object> (which incidentally is how ExpandoObject, which is often used with dynamic to have objects that behave more like javascrpt objects, works behind the scenes). This would be slower and less type-safe than if you created a class for the object needed, but can work.
The problem on an anoynmous property is: how do you get/set it?
Suppose it would work:
class MyClass
{
public MyField = new { TheValue = "Hello World" };
}
Now in your consuming code you´d write code to read the code:
MyClass m = new MyClass();
m.MyField.TheValue = "newValue";
How was this different from having a type for MyField? All you´d get is that you can omit two or three lines of code whilst gaining nothing. But I think you might produce many problems as no-one knows what he can assign to/expect from that member.
Furthermore you can´t do much with an anonymous object, basically you can just set it and read it. There are no methods (except Equalsand GetHashCode inherited from object) that you can call so the opportunities are quite low.
Last but not least an anonymous object is usually used as temporaryily, for example within a Select-statement. When you use it you say: this type is going to be used only within the current specific scope and can be ignored by the entire world as internal implementation-detail. Creating a property of an anonymous type will expose such a detail to the outside. Of course you could argue that the designers could at least allow them for private members, but I guess doing so would bypass the complete concept of accessability for nothing.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
What’s the point of the var keyword?
Use of var keyword in C#
I understand how IEnumerable<...> for a datatype can make the code a little less readable or how nested generics can seem a little daunting. But aside from code readability, are there advantages to using var instead of the explicit type? It seems like by using the explicit type, you'd better convey what the variable is capable of because you know what it is.
If it's a workplace coding standard, I use it for the sake of teamwork. In my own projects however, I prefer to avoid the user of var.
The point of var is to allow anonymous types, without it they would not be possible and that is the reason it exists. All other uses I consider to be lazy coding.
Using var as the iterator variable for a foreach block is more type safe than explicit type names. For example
class Item {
public string Name;
}
foreach ( Item x in col ) {
Console.WriteLine(x.Name);
}
This code could compile without warnings and still cause a runtime casting error. This is because the foreach loop works with both IEnumerable and IEnumerable<T>. The former returns values typed as object and the C# compiler just does the casting to Item under the hood for you. Hence it's unsafe and can lead to runtime errors because an IEnumerable can contain objects of any type.
On the other hand the following code will only do one of the following
Not compile because x is typed to object or another type which does not have a Name field / property
Compile and be guaranteed to not have a runtime cast error while enumerating.
The type of 'x' will be object in the case of IEnumerable and T in the case of IEnumerable<T>. No casting is done by the compiler.
foreach ( var x in col ) {
Console.WriteLine(x.Name);
}
I like it, especially in unit tests, because as the code evolves I only have to fix up the right-hand side of the declaration/assignment. Obviously I also have to update to reflect the changes in usage, but at the point of declaration I only have to make one change.
It produces no meaningful change in the emitted IL. It is merely a code style preference.
I, for one, like it, especially when dealing with types that have long, generic, almost unreadable names such as Dictionary<string, IQueryable<TValue1, TValue2>>[].
The var is just a syntactic sugar. It is always known at compile time what type the variable is. There are no other advantages of using the var keyword.
There aren't any real differences. Some people suggest using the explicit type because it can make maintaining the code easier. However, people that push for var have the stance that "if we use var, we are forced to use good naming conventions".
Of course if you use vars with the intention of having good naming conventions and that breaks down, it's more painful down the road. (IMO)
public IAwesome { string Whatever { get; } }
public SoCool : IAwesome { public string Whatever { get; } }
public HeyHey
{
public SoCool GetSoCool() { return new SoCool(); }
public void Processy()
{
var blech = GetSoCool();
IAwesome ohYeah = GetSoCool();
// Now blech != ohYeah, so var is blech and ohYeah is IAwesome.
}
}
Besides the readability aspect you mentioned, 'var' also has the benefit of reducing the probability that a trivial code change will break other parts of your code. If you rename a type, for example. Or if you switch to a different type that is mostly compatible with the former type (e.g. changing from Foo[] to IEnumerable) you have much less work to do to get your code back to a compilable state.
You can abstract away the mental complexity of the technicalities to focus purely on the problem domain from your model. you have to make sure your variables are named meaningfully tho.
I wanted to use the var keyword to declare a field in my class however var only seems to work inside methods.
The code I have looks like:
public static Dictionary<string, string> CommandList = new Dictionary<string, string>{};
and I wanted to have:
public static var CommandList = new Dictionary<string, string>
How come this isn't possible?
My article on the subject:
Why no var on fields?
To summarize:
If we have "var" fields then the type of the field cannot be determined until the expression is analyzed, and that happens after we already need to know the type of the field.
What if there are long chains, or even cycles in those references? All of those algorithms would have to be rewritten and tested in a world where top-level type information is being determined from them rather than being consumed by them.
If you have "var" fields then the initializer could be of anonymous type. Suppose the field is public. There is not yet any standard in the CLR or the CLS about what the right way to expose a field of anonymous type is.
From the C# reference
Beginning in Visual C# 3.0, variables
that are declared at method scope
can have an implicit type var.
Also from The C# Programming Reference
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.
It just isn't intended for the usage you have in mind.
It's primary aim is to allow the support of anonymous types in your code, with the added advantage of allowing a nice terse way of specifying local variables.
The short answer is because the spec says it's not legal. ;-)
Generally, this is not what you want to do anyway. The type of the member should be IDictionary<string, string> not Dictionary<string, string>. It's a small nit but generally it's better to use an interface in an externally visible object so you can change the type later without affecting the clients of the code. The compiler is just giving you a little nudge to guide you that direction.
This question already has answers here:
Closed 13 years ago.
Duplicate:
What to use var or object name type
I couldn't understand the need of var keyword in C# 3.0 What is the advantage in using it.
i saw this question but did not understand the real purpose of using it
It's mostly present for LINQ, when you may use an anonymous type as the projection:
var query = from person in employees
where person.Salary > 10000m
select new { FullName=person.Name, person.Department };
Here the type of query can't be declared explicitly, because the anonymous type has no name. (In real world cases the anonymous type often includes values from multiple objects, so there's no one named class which contains all the properties.)
It's also practically useful when you're initializing a variable using a potentially long type name (usually due to generics) and just calling a constructor - it increases the information density (reduces redundancy). There's the same amount of information in these two lines:
List<Func<string, int>> functions = new List<Func<string, int>>();
var functions = new List<Function<string, int>>();
but the second one expresses it in a more compact way.
Of course this can be abused, e.g.
var nonObviousType = 999999999;
but when it's obvious what the type's variable is, I believe it can significantly increase readability.
The primary reason for its existence is the introduction of anonymous types in C#. You can construct types on the fly that don't have a name. How would you specify their name? The answer: You can't. You just tell the compiler to infer them for you:
var user = users.Where(u=> u.Name == "Mehrdad")
.Select(u => new { u.Name, u.Password });
It's a shorthand way of declaring a var. Although "int i = new int()" isn't too much to type, when you start getting to longer types, you end up with a lot of lines that look like:
SomeReallyLong.TypeName.WithNameSpaces.AndEverything myVar = new SomeReallyLong.TypeName.WithNameSpaces.AndEverything();
It eventually occurred to someone that the compiler already knew what type you were declaring thanks to the information you were using to initialize the var, so it wouldn't be too much to ask to just have the compiler do the right thing here.
Here are a couple of advantages
Less typing with no loss of functionality
Increases the type safety of your code. A foreach loop using an iteration variable which is typed to var will catch silently casts that are introduced with explicit types
Makes it so you don't have to write the same name twice in a variable declaration.
Some features, such as declaring a strongly typed anonymous type local variable, require the use of var
Shameless self promotion. I wrote a blog entry on this subject awhile back that dived into when I thought the use of var was appropriate and contains relative information to this topic.
http://beta.blogs.msdn.com/jaredpar/archive/2008/09/09/when-to-use-type-inference.aspx
Linq expressions don't return a predefined type, so you need a 'generic' variable declaration keyword to capture that and other places where anonymous types are used.
Used carefully, it can make refactoring easier by decoupling a method's return type from the variable that captures it.
Having to put the same name on the same line twice for the same statement is really kind of silly. It's a pain to type something like this:
.
ReallyLongTypeName<SomeOtherLongTypeName> MyVariable = new ReallyLongTypeName<SomeOtherLongTypeName>();
In short:
minimize the need for typing the variable type twice
essential in supporting anonymous types, e.g. as returned by LINQ queries
The real need for the var keyword was to support anonymous types in C# 3.0--which in turn were required to properly support LiNQ (Language Integrated Querying).
Without using var you could never do something like this:
var person = new { Name = "Peter", Age=4};
Which means that you couldn't execute execute the following linq query because you wouldn't know how to assign it to a variable:
[var/sometype] dogsFixedQuery = from myDog in kennel select new {dogName = myDog.FirstName + " " + myDog.OwnerLastName, myDog.IsNeutered, dogLocation = kennel.Address};
The utility of anonymous types will be more apparent if you start to create more complex linq queries with multiple levels of returns and joins.
The fact that you can use var in other ways to avoid typing out something like IEnumerable<Dictionary<List<string>,IOrderedCollection<DateTime>> myBadDesign = getBadDesignController().BadDesignResults("shoppingCart");
is just a side-effect/bonus in case you're a lazy typer =)
There are cons for readability if you start calling vars in disparate locations but if you're using var for a strong type and the compiler can determine the type of your variable than any reader should be able to determine it as well.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What’s the point of the var keyword?
Hello everyone,
I want to confirm whether my understanding is correct. If I do not use LINQ, then the only benefit of using var is to make brevity? Is that correct understanding?
No, you can use var to construct anonymous types, regardless of whether or not you're using LINQ:
var anon = new { Name = "Anonymous", Age = 42 };
It's also easier for working with types like this. When you have very long generic types, the type name can get in the way of visually identifying the variable name as part of a declaration.
Dictionary<string, Dictionary<int, ICollection<object>>>
especially if you go back through and change it to
Dictionary<string, IDictionary<int, ICollection<object>>>
From msdn:
Beginning in Visual C# 3.0, variables
that are declared at method scope can
have an implicit type var. An
implicitly typed local variable is
strongly typed just as if you had
declared the type yourself, but the
compiler determines the type. The
following two declarations of i are
functionally equivalent:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
MSDN Link Here
If you're not using LINQ, var allows you to only declare the type of the variable once, instead of twice.
Example
var myObject = new MyObject();
vs
MyObject myObject = new MyObject();
This can only be done locally, and is also useful for declaring anonymous types.
Example
var myAnon = new { Name = "Something", Count = 45 };
Other than for LINQ queries I would be very cautious in using the var keyword. There are specific instance when you just need an anonymous type but this is few and far between I think. Var can lead to very confusing code as you have no idea what the type you are dealing with when reading the code unless you use the intellisense crutch.
It worries me more and more that I see so many snippets and bits of code that do the following... it's lazy and not what the var keyword was intended for:
// Not too bad but still shouldn't be done because the only gain you have is keystrokes
var Something = new SomeObject();
// Type here is not obvious, are you getting an int, double, custom object back???
var Something = GetLengthOfSpaghettiCode();
So use it for LINQ... use it for anonymous types (if you do use anonymous types outside of LINQ you should really scrutinize why you need to).
Quote from MSDN (very last line of article) regarding use of var:
However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.
Don't use it as a short cut to save keystrokes, the next guy looking at your code will appreciate it.
Pretty much, yes. var may be used wherever the compiler can infer the type of the variable from whatever value you are assigning to it. (The type inference rules are quite complex however, so you may want to read the C# specification for a full understandin.)
It's not quite correct in that the var keyword is required for defining anonymous types. For example:
var foo = new { abc = 1, def = 2 };
which can be used outside of LINQ queries as well as inside, of course.
I don't think using var should be a problem - and I prefer it for exactly the reasons of code readability. First of all, var is only syntactic sugar and just gets compiled away to a proper type when IL is emitted. And as far as the code readability goes, it makes more sense to focus on the purpose the variable is used for, and how it is assigned than just its type. VS .NET editor shows the type in the line following it anyway - if you just hover on it. So this shouldn't be a problem at all. And as far as the debugging goes - if you see Autos/Local/Watch windows - they display the types of all the members.
It makes more sense for me to see code like this:
var customers = GetCustomerList();
foreach (var customer in customers)
{
customer.ProcessOrders();
}
as opposed to
List<CustomerObjectDeserializedFromWebService> customers = GetCustomers();
foreach (CustomerObjectDeserializedFromWebService customer in customers)
{
customer.ProcessOrders();
}
var is in its fairness limited to using in local variable declarations which are also initialized at the time of declaration. And in that one case, if you omit the actual type it definitely improves readability IMO.
EDIT: And it would unfair on my part not to warn against the usages as below:
var x = 20;
This is not good; when the literal is applicable to multiple types, you need to know the default type of the literal and hence understand what is infered for the type of x. Yes, by all means, I would avoid such declarations.
I believe it is also used in the WCF (Windows communication Foundation) when dealing with data obtained via webservices and the like.
I've also found that the use of var also eases refactoring in low-coupled designs. This is because we tend to strong type variables, but normally the code that follows is expecting weaker types. Using var you'll offset type changes to the compiler.