use of var

P

Peter

Hi

I see "var" a lot in code. I understand that it can be used when
dealing with "anonymous types" in LINQ (I think).

But most times I see it like the following examples:

XmlDocument doc = new XmlDocument();
var root = doc.CreateElement("Message");

Why "var" here - why not XmlElement?


Or:

(obtaining a single user with LoginName == "admin")

var user = UserList.Single(u => u.LoginName == "admin");

Why "var" here, and not the actual type "User"?


Does using var in these types of situations have any advantages (over
and above typing a few extra characters for the real type name)?

Does it make it harder to read and understand the code if var is used
as above (it does for me at least)?


Thanks,
Peter
 
J

Jeff Johnson

Does using var in these types of situations have any advantages (over
and above typing a few extra characters for the real type name)?

Does it make it harder to read and understand the code if var is used
as above (it does for me at least)?

You're not alone. We've been over this before (I started one of the
threads), and in my opinion, the uses of var that you described are just
plain laziness.
 
A

andy.johnstone

You're not alone. We've been over this before (I started one of the
threads), and in my opinion, the uses of var that you described are just
plain laziness.

I don't think it's fair to call something lazy because you personally
thing it's "wrong" for some reason. If I have to type a long type
name or var... var to me makes it more clear, because the context
usually tells me what the type will be.. or intelligence. This is the
same line of thinking where old-timers say using an attached debugger
is lazy, and the "right" way to do it is using printf...
 
P

Peter Morris

var is fine in my opinion as long as it's obvious.

var x = y.CreateClone();

No idea, what that is, but this is clear (despite the crap variable naming)

Specification x = y.CreateClone();


however, this is equally clear

var x = new ReaderWriterLockSlim();

and fits into a newsgroup post much better.


As for it being lazy......meh :)
 
A

Ajay

You're not alone. We've been over this before (I started one of the
threads), and in my opinion, the uses of var that you described are just
plain laziness.


var reminds me of void* in C/C++. Unless there are advantages of using
it, I wouldnt use it.
 
P

Pavel Minaev

Hi

I see "var" a lot in code. I understand that it can be used when
dealing with "anonymous types" in LINQ (I think).

But most times I see it like the following examples:

XmlDocument doc = new XmlDocument();
var root = doc.CreateElement("Message");

Why "var" here - why not XmlElement?

Or:

(obtaining a single user with LoginName == "admin")

var user = UserList.Single(u => u.LoginName == "admin");

Why "var" here, and not the actual type "User"?

Oh my, that counts as a "flamebait" in this newsgroup :)
Does using var in these types of situations have any advantages (over
and above typing a few extra characters for the real type name)?

Does it make it harder to read and understand the code if var is used
as above (it does for me at least)?

There are, essentially, 3 schools of thought:

1) Use "var" only when needed (i.e. with anonymous types).
2) Use "var" where the actual type is obvious from the initializer
(the definition of "obvious" varies).
3) Use "var" everywhere it's shorter (essentially all locals, with
exception of those used for out/ref arguments, or initialized with a
null or a delegate).

There isn't much to say about #1 - it's pretty obvious what it is
about.


#2 is interesting, and seems to be what most C# developers subscribe
to (at least from my personal anecdotal experience). For example, it
would seem that the following is crystal clear:

var list = new List<int>();

There's no purpose in repeating the type on the same line of code
twice - it really doesn't help to read code. The same goes for casts:

var form = (Form)button.Parent;

However, the following are less obvious - some consider them
appropriate, some do not:

var foo = FooFactory.CreateFoo();
var bar = foo.Get<Bar>();


I used to be in #2 camp, but have gravitated to #3 as time went by...
I have my reasons for that, but I can't help thinking that perhaps the
underlying motive is still laziness, and the rest are just post-facto
rationalizations :) Nonetheless, here's how the thinking goes...

The major point of both #1 and #2 is that knowledge of types of
expressions and variables matters at all times. I claim that, in
practice, it does not - static typing should serve as an instrument to
help catch typos and non-sensible things (barking cows and mooing
dogs, etc), but it can do so perfectly well with type inference, as
evidenced by many FP languages - ML family and Haskell in particular.
Meanwhile, what the programmer should care about is the meaning - and,
for the code to be truly readable, it should be clear without knowing
the precise types. Descriptive identifiers help much more than
explicit type annotations there, and in most cases, are perfectly
enough to achieve good readability which isn't further improved by
explicit typing. For example:

var employee = People.FindByName("John");
var manager = employee.Manager;
...

In the above code, do you really need to know the types of variables
involved? Or is the intent of the code entirely clear through the
names of variables, members, and methods? I believe the latter is true
- and it will hold true so long as the naming is good; so if it ever
breaks down, and you become confused by "var", that means that
somewhere else your naming is not clear enough, and _that_ should be
improved. Well, or else you have methods that span 2+ screens - at
which point "var" is the least of your problems.

By the way, I wonder how many of people in #2 and especially #1 camps
regard "let" in LINQ queries, which provides no way to specify the
type of the variable explicitly... :)
 
D

dunawayc

var is fine in my opinion as long as it's obvious.

var x = y.CreateClone();

No idea, what that is, but this is clear (despite the crap variable naming)

Specification x = y.CreateClone();

however, this is equally clear

var x = new ReaderWriterLockSlim();

and fits into a newsgroup post much better.

As for it being lazy......meh :)

I agree. Another place where var can make things a little more
readable is if the type name is long:

ExtraLongTypeName t = new ExtraLongTypeName();

as opposed to:

var t = new ExtraLongTypeName();

As long readability is not hindered, I see no reason not to use var.

Chris
 
P

Peter Morris

ExtraLongTypeName t = new ExtraLongTypeName();

And contrary to what some people might say it isn't about being too lazy to
type. Once I have typed "ExtraLongTypeName t = new " VS will suggest the
class name and I can just hit tab, so it actually takes more keypresses.
The reason I use it is simply because I find I can read the line quicker if
it just says "var t = .........". Seeing as I am going to read what is to
the right of the = sign anyway I see no point in declaring the type to the
left of it, the "var" merely tells me this is a local variable.
 
A

Ajay

But I can't say that I find it all that worthwhile to argue strenuously  
against the use of "var" in situations where it's not strictly needed.  In  
the end, it's not the sort of thing that's likely to make or break the  
quality of the code and is mainly just a matter of personal preference (I 
put it into the same category as bracing habits).

I was speaking strictly from understanding the code. It makes someone
not familiar with the code to think more than required as you would
need to know the type as its not explicit. As a code writer its not a
big deal at least when you are coding.

I havent used it at all so far but my first impressions arent very
friendly towards it. However if there are benefits(performance etc)
than it is worth the effort/confusion.
 
I

Ignacio Machin ( .NET/ C# MVP )

Hi

I see "var" a lot in code. I understand that it can be used when
dealing with "anonymous types" in LINQ (I think).

But most times I see it like the following examples:

XmlDocument doc = new XmlDocument();
var root = doc.CreateElement("Message");

Why "var" here - why not XmlElement?

Or:

(obtaining a single user with LoginName == "admin")

var user = UserList.Single(u => u.LoginName == "admin");

Why "var" here, and not the actual type "User"?

Does using var in these types of situations have any advantages (over
and above typing a few extra characters for the real type name)?

Does it make it harder to read and understand the code if var is used
as above (it does for me at least)?

Thanks,
Peter

IMHO it makes the code less readable and more cumbersome to
understand. For example i nyour example above, by seenig the line you
do not know the type of user , it's also more difficult to get to the
defiintion of the type.
 
I

Ignacio Machin ( .NET/ C# MVP )

You're not alone. We've been over this before (I started one of the
threads), and in my opinion, the uses of var that you described are just
plain laziness.

or trying to write "cool" code
 
A

andy.johnstone

var reminds me of void* in C/C++. Unless there are advantages of using
it, I wouldnt use it.

Ok... but it's nothing like void* at all. It's still strongly typed.
It doesn't lead to the possible bugs that would arise from using
void*, nor can you even use it as a parameter or return type. When
compiled, it's identical to using the actual type name in place of
var. So the readability boils down to the context of the code in
question.
 
A

Ajay

I see no difference in understanding between:

     Form form = new Form();

and

     var form = new Form();

Of course. But not everyone is going to follow the simplistic way you
have presented. Besides, over time var form can become "var
somethingElse" while "Form somethingElse" is still good.
That said, I do see a difference between:

     Control control = new TextBox();

and

     var control = new TextBox();

But in either case, I think that the fundamental understanding of the code  
is the same.  

No, its not. Second example assumes the reader to know that Control is
a type and is implied by that statement. You assume that coder did
what you as a reader think they should do by naming the variable
"control".

Also it forces you know what type a method returns:

var someType = SomeMethodReturningSomeType();

This is a step that coder has to do in order to name the variable
someType. Why not simply use it as is then:

SomeType someType = SomeMethodReturningSomeType();
 And I feel that using  
"var" can only take _away_ understanding of the code, never add to it.

That pretty much sums up why I would not use it and would not advocate
use of it.
But I agree with the others who point out that in lots of cases, "var"  
doesn't in fact cause any reduction in understanding of the code as  
compared to the alternative.

Correct and that assumes that others using it are aware of that
issue. All it tells me is people using it are being "cool" :)
 
A

Ajay

Ok... but it's nothing like void* at all.  It's still strongly typed.

I do understand that. Compiler is happy with it but it adds an extra
step for the reader.
It doesn't lead to the possible bugs that would arise from using
void*, nor can you even use it as a parameter or return type.  When
compiled, it's identical to using the actual type name in place of
var.  So the readability boils down to the context of the code in
question.

My point was readability.
 
G

G.S.

I do understand that. Compiler is happy with it but it adds an extra
step for the reader.


My point was readability.

I think var's usage should be limited to what they had in mind when
they introduced it.

I tend to agree that all the "Readability" examples above require the
extra step of knowing or finding out what the right-hand side of the
statement means. It is easy sometimes (the Form example), but it's
still an extra step and the alternative is equally easy.
 
A

Ajay

I tend to agree that all the "Readability" examples above require the
extra step of knowing or finding out what the right-hand side of the
statement means. It is easy sometimes (the Form example), but it's
still an extra step and the alternative is equally easy.

That is how I see it as well. But there must have been a reason that
it was introduced.
 
A

Ajay

Yes, it is.


I assumed no such thing.

You have completely missed my point.  I wrote that the FUNDAMENTAL
understanding of the code is the same.  That is, in either case, the
reader knows that you're creating a TextBox and will be doing something
with it.  There are other aspects of understanding, less FUNDAMENTAL and
so much less important, that are affected.  But the FUNDAMENTAL aspects
are the same.
OK.

The "var" example is deficient only in that it doesn't show in the
declaration that the code that uses the variable will in fact not be using
any of the things unique to TextBox, but rather only the members found in
the Control base class.  This is hardly a FUNDAMENTAL aspect of the
understanding one would have of the code.  It's icing on the cake at best.


As a coder, fundamental alone doesnt cut it. Its good enough for a
designer but not to a coder. So it may help a designer reading the
code but for a peer coder, its still not good enough.
And as far as he question of whether the reader knows that "Control is a
type" goes, that's entirely irrelevant to the point here.  The only place
in my example that the word "Control" appears is in the non-"var" example
and it's obvious from the context that it's a type.



That's nothing like the examples I posted.  Instantiation via "new
SomeType()" always returns an instance of SomeType.  I wasn't writing
about a method with a return value, I was writing specifically about the
case where you have included the actual type name in the initialization.



Why not indeed?  But how does that have anything to do with what I wrote?

Nothing directly. Yours just didnt address issues which make using var
as "not a nice thing for others".
 
P

Pavel Minaev

I think var's usage should be limited to what they had in mind when
they introduced it.

You assume that the C# design team has a definite agreement on how
"var" should be used. I cannot definitely claim this to be either way,
but, judging from the blogs of people involved, this doesn't seem to
be true. Even the annotated "C# Programming Language" book has various
different opinions on the subject represented in annotations. That's
what is so flame-inducing about this topic - unlike many other things
in C#/.NET land, there's no definite guide here, so you can't just
say, "right or wrong, this is the established convention". There's
none (yet?).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top