Implicit typing; why just local variables? - c#

Does anyone know or care to speculate why implicit typing is limited to local variables?
var thingy = new Foo();
But why not...
var getFoo() {
return new Foo();
}

Eric Lippert did an entire blog post on the subject.
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/why-no-var-on-fields
In summary, the main problem is that it would have required a major re-architecture of the C# compiler to do so. Declarations are currently processed in a single pass manner. This would require multiple passes because of the ability to form cycles between inferred variables. VB.NET has roughly the same problem.

Jared has a fantastic link in his answer, to a fantastic topic.
I think it does not answer the question explicitly.
Why not?
var getFoo() {
return new Foo();
}
The reason for this is:
What if?
class Foo {}
var GetFoo() {
return GetBar();
}
var GetBar() {
return GetBaz();
}
var GetBaz() {
return new Foo();
}
You could deduce that GetFoo is going to return Foo, but you will have to trace through all the calls that method makes and its children makes just to infer the type. As it stands the C# compiler is not designed to work in this way. It needs method and field types early in the process before the code that infers types can run.
On a purely aesthetic level I find the var definitions on methods confuse things. Its one place where I think being explicit always helps, it protects you from shooting your self in the foot by accidentally returning a type that causes your signature and a ton of other dependent method signatures to change. Worst still, you could potentially change all you signatures of a method chain without even knowing you did so if you return the value of a method that returns object and happened to be lucky.
I think var methods are best left for dynamic languages like Ruby

Because it is much easyer to do. If you were to inference all types, one would need something like Hindley Milner type inference system which will in make your beloved C# into Haskel derivative language.

Essentially, the issue you are running into is that C# (thus far) is a statically typed language. A local variable defined as var is still statically typed, but syntactically hidden. A method returning var, on the other hand, has many implications. It becomes more of an interface for usage, and you don't gain anything by using var.

you can use in vs 2010 Dynamic
Dynamic getFoo() {
return new Foo();
}

I think it's because the scope of that implied type is much wider and therefore more likely to cause problems than within the scope of a single method.

Related

Shall programmer use "foreach var" instead "foreach AnyClass" in C#? [duplicate]

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

using var instead of specific type [duplicate]

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

Use of "var" type in variable declaration

Our internal audit suggests us to use explicit variable type declaration instead of using the keyword var. They argue that using of var "may lead to unexpected results in some cases".
I am not aware of any difference between explicit type declaration and using of var once the code is compiled to MSIL.
The auditor is a respected professional so I cannot simply refuse such a suggestion.
How about this...
double GetTheNumber()
{
// get the important number from somewhere
}
And then elsewhere...
var theNumber = GetTheNumber();
DoSomethingImportant(theNumber / 5);
And then, at some point in the future, somebody notices that GetTheNumber only ever returns whole numbers so refactors it to return int rather than double.
Bang! No compiler errors and you start seeing unexpected results, because what was previously floating-point arithmetic has now become integer arithmetic without anybody noticing.
Having said that, this sort of thing should be caught by your unit tests etc, but it's still a potential gotcha.
I tend to follow this scheme:
var myObject = new MyObject(); // OK as the type is clear
var myObject = otherObject.SomeMethod(); // Bad as the return type is not clear
If the return type of SomeMethod ever changes then this code will still compile. In the best case you get compile errors further along, but in the worst case (depending on how myObject is used) you might not. What you will probably get in that case is run-time errors which could be very hard to track down.
Some cases could really lead to unexpected results. I'm a var fan myself, but this could go wrong:
var myDouble = 2;
var myHalf = 1 / myDouble;
Obviously this is a mistake and not an "unexpected result". But it is a gotcha...
var is not a dynamic type, it is simply syntactic sugar. The only exception to this is with Anonymous types. From the Microsoft Docs
In many cases the use of var is optional and is just a syntactic convenience. However, when a variable is initialized with an anonymous type you must declare the variable as var if you need to access the properties of the object at a later point.
There is no difference once compiled to IL unless you have explicitly defined the type as different to the one which would be implied (although I can't think of why you would). The compiler will not let you change the type of a variable declared with var at any point.
From the Microsoft documentation (again)
An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type
In some cases var can impeed readability. More Microsoft docs state:
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.
In the non-generic world you might get different behavior when using var instead of the type whenever an implicit conversion would occur, e.g. within a foreach loop.
In the example below, an implicit conversion from object to XmlNode takes place (the non-generic IEnumerator interface only returns object). If you simply replace the explicit declaration of the loop variable with the var keyword, this implicit conversion no longer takes place:
using System;
using System.Xml;
class Program
{
static void Foo(object o)
{
Console.WriteLine("object overload");
}
static void Foo(XmlNode node)
{
Console.WriteLine("XmlNode overload");
}
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<root><child/></root>");
foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
Foo(node);
}
foreach (var node in doc.DocumentElement.ChildNodes)
{
// oops! node is now of type object!
Foo(node);
}
}
}
The result is that this code actually produces different outputs depending on whether you used var or an explicit type. With var the Foo(object) overload will be executed, otherwise the Foo(XmlNode) overload will be. The output of the above program therefore is:
XmlNode overload
object overload
Note that this behavior is perfectly according to the C# language specification. The only problem is that var infers a different type (object) than you would expect and that this inference is not obvious from looking at the code.
I did not add the IL to keep it short. But if you want you can have a look with ildasm to see that the compiler actually generates different IL instructions for the two foreach loops.
It's an odd claim that using var should never be used because it "may lead to unexpected results in some cases", because there are subtleties in the C# language far more complex than the use of var.
One of these is the implementation details of anonymous methods which can lead to the R# warning "Access to modified closure" and behaviour that is very much not what you might expect from looking at the code. Unlike var which can be explained in a couple of sentences, this behaviour takes three long blog posts which include the output of a disassembler to explain fully:
The implementation of anonymous methods in C# and its consequences (part 1)
The implementation of anonymous methods in C# and its consequences (part 2)
The implementation of anonymous methods in C# and its consequences (part 3)
Does this mean that you also shouldn't use anonymous methods (i.e. delegates, lambdas) and the libraries that rely on them such as Linq or ParallelFX just because in certain odd circumstances the behaviour might not be what you expect?
Of course not.
It means that you need to understand the language you're writing in, know its limitations and edge cases, and test that things work as you expect them to. Excluding language features on the basis that they "may lead to unexpected results in some cases" would mean that you were left with very few language features to use.
If they really want to argue the toss, ask them to demonstrate that a number of your bugs can be directly attributed to use of var and that explicit type declaration would have prevented them. I doubt you'll hear back from them soon.
They argue that using of var "may lead
to unexpected results in some cases".to unexpected results in some cases".
If unexpected is, "I don't know how to read the code and figure out what it is doing," then yes, it may lead to unexpected results. The compiler has to know what type to make the variable based on the code written around the variable.
The var keyword is a compile time feature. The compiler will put in the appropriate type for the declaration. This is why you can't do things like:
var my_variable = null
or
var my_variable;
The var keyword is great because, you have to define less information in the code itself. The compiler figures out what it is supposed to do for you. It's almost like always programming to an interface when you use it (where the interface methods and properties are defined by what you use within the declaration space of the variable defined by var). If the type of a variable needs to change(within reason of course), you don't need to worry about changing the variable declaration, the compiler handles this for you. This may sound like a trivial matter, but what happens if you have to change the return value in a function, and that function is used all throughout the program. If you didn't use var, then you have to find and replace every place that variable is called. With the var keyword, you don't need to worry about that.
When coming up with guidelines, as an auditor has to do, it is probably better to err on the side of fool safe, that is white listing good practices / black listing bad practices as opposed to telling people to simply be sensible and do the right thing based on an assessment of the situation at hand.
If you just say "don't use var anywhere in code", you get rid of a lot of ambiguity in the coding guidelines. This should make code look & feel more standardized without having to solve the question of when to do this and when to do that.
I personally love var. I use it for all local variables. All the time. If the resulting type is not clear, then this is not an issue with var, but an issue with the (naming of) methods used to initialize a variable...
I follow a simple principle when it comes to using the var keyword. If you know the type beforehand, don't use var.
In most cases, I use var with linq as I might want to return an anonymous type.
var best using when you have obviously declaration
ArrayList<Entity> en = new ArrayList<Enity>()
complicates readability
var en = new ArrayList<Entity>()
Lazy, clear code, i like it
I use var only where it is clear what type the variable is, or where it is no need to know the type at all (e.g. GetPerson() should return Person, Person_Class, etc.).
I do not use var for primitive types, enum, and string. I also do not use it for value type, because value type will be copied by assignment so the type of variable should be declared explicitly.
About your auditor comments, I would say that adding more lines of code as we have been doing everyday also "lead to unexpected results in some cases". This argument validity has already proven by those bugs we created, therefore I would suggest freezing the code base forever to prevent that.
using var is lazy code if you know what the type is going to be. Its just easier and cleaner to read. When looking at lots and lots of code, easier and cleaner is always better
There is absolutely no difference in the IL output for a variable declaration using var and one explicitly specified (you can prove this using reflector). I generally only use var for long nested generic types, foreach loops and anonymous types, as I like to have everything explicitly specified. Others may have different preferences.
var is just a shorthand notation of using the explicit type declaration.
You can only use var in certain circumstances; You'll have to initialize the variable at declaration time when using var.
You cannot assign a variable that is of another type afterwards to the variable.
It seems to me that many people tend to confuse the 'var' keyword with the 'Variant' datatype in VB6 .
The "only" benefit that i see towards using explicit variable declaration, is with well choosen typenames you state the intent of your piece of code much clearer (which is more important than anything else imo). The var keyword's benefit really is what Pieter said.
I also think that you will run into trouble if you declare your doubles without the D on the end. when you compile the release version, your compiler will likely strip off the double and make them a float to save space since it will not consider your precision.
var will compile to the same thing as the Static Type that could be specified. It just removes the need to be explicit with that Type in your code. It is not a dynamic type and does not/can not change at runtime. I find it very useful to use in foreach loops.
foreach(var item in items)
{
item.name = ______;
}
When working with Enumerations some times a specific type is unknown of time consuming to lookup. The use of var instead of the Static Type will yeald the same result.
I have also found that the use of var lends it self to easier refactoring. When a Enumeration of a different type is used the foreach will not need to be updated.
Use of var might hide logical programming errors, that otherwise you would have got warning from the compiler or the IDE. See this example:
float distX = innerDiagramRect.Size.Width / (numObjInWidth + 1);
Here, all the types in the calculation are int, and you get a warning about possible loss of fraction because you pick up the result in a float variable.
Using var:
var distX = innerDiagramRect.Size.Width / (numObjInWidth + 1);
Here you get no warning because the type of distX is compiled as int. If you intended to use float values, this is a logical error that is hidden to you, and hard to spot in executing unless it triggers a divide by zero exception in a later calculation if the result of this initial calculation is <1.

When should one use dynamic keyword in c# 4.0?

When should one use dynamic keyword in c# 4.0?.......Any good example with dynamic keyword in c# 4.0 that explains its usage....
Dynamic should be used only when not using it is painful. Like in MS Office libraries. In all other cases it should be avoided as compile type checking is beneficial. Following are the good situation of using dynamic.
Calling javascript method from Silverlight.
COM interop.
Maybe reading Xml, Json without creating custom classes.
How about this? Something I've been looking for and was wondering why it was so hard to do without 'dynamic'.
interface ISomeData {}
class SomeActualData : ISomeData {}
class SomeOtherData : ISomeData {}
interface ISomeInterface
{
void DoSomething(ISomeData data);
}
class SomeImplementation : ISomeInterface
{
public void DoSomething(ISomeData data)
{
dynamic specificData = data;
HandleThis( specificData );
}
private void HandleThis(SomeActualData data)
{ /* ... */ }
private void HandleThis(SomeOtherData data)
{ /* ... */ }
}
You just have to maybe catch for the Runtime exception and handle how you want if you do not have an overloaded method that takes the concrete type.
Equivalent of not using dynamic will be:
public void DoSomething(ISomeData data)
{
if(data is SomeActualData)
HandleThis( (SomeActualData) data);
else if(data is SomeOtherData)
HandleThis( (SomeOtherData) data);
...
else
throw new SomeRuntimeException();
}
As described in here dynamics can make poorly-designed external libraries easier to use: Microsoft provides the example of the Microsoft.Office.Interop.Excel assembly.
And With dynamic, you can avoid a lot of annoying, explicit casting when using this assembly.
Also, In opposition to #user2415376 ,It is definitely not a way to handle Interfaces since we already have Polymorphism implemented from the beginning days of the language!
You can use
ISomeData specificData = data;
instead of
dynamic specificData = data;
Plus it will make sure that you do not pass a wrong type of data object instead.
Check this blog post which talks about dynamic keywords in c#. Here is the gist:
The dynamic keyword is powerful indeed, it is irreplaceable when used with dynamic languages but can also be used for tricky situations while designing code where a statically typed object simply will not do.
Consider the drawbacks:
There is no compile-time type checking, this means that unless you have 100% confidence in your unit tests (cough) you are running a risk.
The dynamic keyword uses more CPU cycles than your old fashioned statically typed code due to the additional runtime overhead, if performance is important to your project (it normally is) don’t use dynamic.
Common mistakes include returning anonymous types wrapped in the dynamic keyword in public methods. Anonymous types are specific to an assembly, returning them across assembly (via the public methods) will throw an error, even though simple testing will catch this, you now have a public method which you can use only from specific places and that’s just bad design.
It’s a slippery slope, inexperienced developers itching to write something new and trying their best to avoid more classes (this is not necessarily limited to the inexperienced) will start using dynamic more and more if they see it in code, usually I would do a code analysis check for dynamic / add it in code review.
Here is a recent case in which using dynamic was a straightforward solution. This is essentially 'duck typing' in a COM interop scenario.
I had ported some code from VB6 into C#. This ported code still needed to call other methods on VB6 objects via COM interop.
The classes needing to be called looked like this:
class A
{
void Foo() {...}
}
class B
{
void Foo() {...}
}
(i.e., this would be the way the VB6 classes looked in C# via COM interop.
Since A and B are independent of each other you can't cast one to the other, and they have no common base class (COM doesn't support that AFAIK and VB6 certainly didn't. And they did not implement a common interface - see below).
The original VB6 code which was ported did this:
' Obj must be either an A or a B
Sub Bar(Obj As Object)
Call Obj.Foo()
End Sub
Now in VB6 you can pass things around as Object and the runtime will figure out if those objects have method Foo() or not. But in C# a literal translation would be:
// Obj must be either an A or a B
void Bar(object Obj)
{
Obj.Foo();
}
Which will NOT work. It won't compile because object does not have a method called "Foo", and C# being typesafe won't allow this.
So the simple "fix" was to use dynamic, like this:
// Obj must be either an A or a B
void Bar(dynamic Obj)
{
Obj.Foo();
}
This defers type safety until runtime, but assuming you've done it right works just fine.
I wouldn't endorse this for new code, but in this situation (which I think is not uncommon judging from other answers here) it was valuable.
Alternatives considered:
Using reflection to call Foo(). Probably would work, but more effort and less readable.
Modifying the VB6 library wasn't on the table here, but maybe there could be an approach to define A and B in terms of a common interface, which VB6 and COM would support. But using dynamic was much easier.
Note: This probably will turn out to be a temporary solution. Eventually if the remaining VB6 code is ported over then a proper class structure can be used.
I will like to copy an excerpt from the code project post, which define that :
Why use dynamic?
In the statically typed world, dynamic gives developers a lot of rope
to hang themselves with. When dealing with objects whose types can be
known at compile time, you should avoid the dynamic keyword at all
costs. Earlier, I said that my initial reaction was negative, so what
changed my mind? To quote Margret Attwood, context is all. When
statically typing, dynamic doesn't make a stitch of sense. If you are
dealing with an unknown or dynamic type, it is often necessary to
communicate with it through Reflection. Reflective code is not easy to
read, and has all the pitfalls of the dynamic type above. In this
context, dynamic makes a lot of sense.[More]
While Some of the characteristics of Dynamic keyword are:
Dynamically typed - This means the type of variable declared is
decided by the compiler at runtime time.
No need to initialize at the time of declaration.
e.g.,
dynamic str;
str=”I am a string”; //Works fine and compiles
str=2; //Works fine and compiles
Errors are caught at runtime
Intellisense is not available since the type and its related methods and properties can be known at run time only. [https://www.codeproject.com/Tips/460614/Difference-between-var-and-dynamic-in-Csharp]
It is definitely a bad idea to use dynamic in all cases where it can be used. This is because your programs will lose the benefits of compile-time checking and they will also be much slower.

Stylecop tells me to add this keyword, but it's redundant - any performance implications?

I use Stylecop for Resharper and whenever I call something in my class, Stylecop tells me to use the this keyword. But the IDE says this is redundant code (which it sure is), so why should I use the this keyword?
Does redundant code mean its not needed (obviously) and the compiler won't even do anything with the this keyword? So I assume the this keyword is just for clarity.
Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET? I assume it is all for clarity as stylecop keeps an eye on this and Fxcop (which I will use later on) keeps an eye on my code's quality from a technical point of view.
Thanks
It's for clarity and to prevent any ambiguity between a class member and a local variable or parameter with the same name.
The IL it compiles to will not be any different.
Most of the time is just for clarity but some times it is required.
using System;
class Foo
{
String bar;
public Foo(String bar)
{
this.bar = bar;
}
}
Here you will need this as it serves to disambiguate between the field bar and the constructor parameter bar. Obviously changing the name of the parameter or field could accomplish the same thing.
In all cases, there is no performance difference with/without the this - the compiler still does it implicitly, injecting a ldarg.0 into the IL.
Just for completeness, there is one other mandatory use of this (excluding disambiguation, ctor-chaining, and passing this to other methods): extension methods. To call an extension method on the current instance, you must qualify with this (even though for a regular method it would be implicit).
Of course, in most cases, you would simply add a regular instance method to the class or a base-class...
class Foo {
void Test() {
this.Bar(); // fine
Bar(); // compiler error
}
}
static class FooExt {
public static void Bar(this Foo foo) { }
}
In C# this is a reference to the current instance of the class (it's me in VB.NET). It's used generally to fully qualify a class member. For example, consider this C# class:
public class MyClass
{
int rate;
private void testMethod()
{
int x;
x = this.rate;
}
}
this isn't required in the code above, but adds instant clarity when reading the code that rate belongs to the class rather than the method (search SO, you'll find lots of opinions about the use of this). It's semantic behavior is the same in VB--and its use doesn't impose a performance penalty.
Apart from the clarity examples provided the only other valid usage of the "this" keyword is to pass the current instance of an object as a paremeter.
It is just for clarity, and one can argue about what is better. Python doesn't support omitting the "self" identifier at all.
Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET?
In JVM for sure (and also for CLR, I'm almost sure) the code for the "this" keyword is always generated, even if that is omitted from the source - so it's like if the this keyword is always added. So, I don't think that any .NET compiler could generate different output, so there can't be a performance penalty.
Then, it depends on the language. For instance JScript (and even JScript.NET) does not allow to omit "this", like Python, because there are functions (so "this.a()" is a method invocation, "a()" is a function invocation), and because the compiler does not know the members of any types - they're only known at runtime (well, this is not an impossible problem to solve indeed, the other issue is more relevant).

Categories

Resources