Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / March 2008

Tip: Looking for answers? Try searching our database.

var for locals

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Peter Morris - 09 Mar 2008 22:41 GMT
var myObj = new MyClass();

What is the purpose of using "var" instead of "MyClass"?
Arne Vajhøj - 09 Mar 2008 22:49 GMT
> var myObj = new MyClass();
>
> What is the purpose of using "var" instead of "MyClass"?

In this case: none.

In general var means that the compile determines the type.

And it is most useful with the nameless types being
returned from LINQ.

Arne
Gilles Kohl [MVP] - 09 Mar 2008 23:06 GMT
>var myObj = new MyClass();
>
>What is the purpose of using "var" instead of "MyClass"?

Not much, really - it saves a bit of typing, more so in examples like

var wordsStartingWithSameLetter = new Dictionary<char, List<string>>();

var really shines in context with (and I guess was invented for) LINQ though -

e.g. (from the MSDN "anonymous types" example):

var productQuery =
   from prod in products
   select new { prod.Color, prod.Price };

foreach (var v in productQuery)
{
   Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}

You have to use "var" here since the type "{ prod.Color, prod.Price }" is
created on the fly by the compiler - you do not know its name. This lets you
change your mind about what you want in the select clause without having to
update (or even create in the first place) a corresponding "data container"
class.

  Regards,
  Gilles.
Jon Skeet [C# MVP] - 09 Mar 2008 23:15 GMT
> var myObj = new MyClass();
>
> What is the purpose of using "var" instead of "MyClass"?

var is necessary when you're using anonymous types, but it has further
readability implications in terms of what you choose to emphasise.

Eric Lippert puts it very well. See
http://csharpindepth.com/ViewNote.aspx?NoteID=61

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

Peter Morris - 10 Mar 2008 10:19 GMT
This is what made me ask:

http://codebetter.com/blogs/jeffrey.palermo/archive/2008/03/09/this-is-how-asp-n
et-mvc-controller-actions-should-be-unit-tested.aspx


In which he has code like

   var repository = new FakeRepository();     var mockViewEngine = new
MockViewEngine();    var controller = new MainController(repository,
mockViewEngine);
Unlike using "var" in LINQ queries I see no benefit here.  In fact I see it
resembling my old BASIC days back in the 1980's

var a = 1;

var b = "2";

var c = a + b;

The answer is "12", not 3 or 12.  I'll stick with strongly typed variables
unless using LINQ I think :-)

Pete
Jon Skeet [C# MVP] - 10 Mar 2008 10:29 GMT
> This is what made me ask:
>
[quoted text clipped - 6 lines]
>     var mockViewEngine = new MockViewEngine();    
>     var controller = new MainController(repository, mockViewEngine);

All of those seem reasonable to me. It's immediately clear what the
type is, because it's on the right hand side - and because the variable
names are clear. (The variable names don't have to explicitly specify
the type, of course, so long as they're clear in intent.)

> Unlike using "var" in LINQ queries I see no benefit here.  In fact I see it
> resembling my old BASIC days back in the 1980's
[quoted text clipped - 4 lines]
>
> var c = a + b;

I might use var for b, but not a or c.

a) Integer literals get trickier, because the type changes depending on
the size of the number.

b) String literals are obviously strings. No ambiguity there. A better
variable name would probably be more help than an explicitly typed
variable here.

c) In this case it's not immediately obvious what the type *or the
behaviour of the expression* is. Again, I'd say this is more due to the
names of the variables than anything else.

> The answer is "12", not 3 or 12.  I'll stick with strongly typed variables
> unless using LINQ I think :-)

You're still using strongly typed variables with var. You're just not
using *explicitly* typed variables. There's a massive difference. I
suspect you may know this, but others may not - I think it's important
to spread the word that "var != Variant" :)

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

Peter Morris - 10 Mar 2008 14:01 GMT
> You're still using strongly typed variables with var. You're just not
> using *explicitly* typed variables. There's a massive difference. I
> suspect you may know this, but others may not - I think it's important
> to spread the word that "var != Variant" :)

I know, but I just don't see a *benefit* to using "var" here except that it
is quicker to type, and seeing as I haven't used less than two fingers to
type since I was about 15 it doesn't really benefit me.  How I hated typing
lessons at the time!

Pete
Jon Skeet [C# MVP] - 10 Mar 2008 14:11 GMT
> > You're still using strongly typed variables with var. You're just not
> > using *explicitly* typed variables. There's a massive difference. I
[quoted text clipped - 5 lines]
> type since I was about 15 it doesn't really benefit me.  How I hated typing
> lessons at the time!

Typing isn't the issue. Information redundancy is the issue.

Does having the type name twice actually make the code clearer? I
wouldn't say it does. The same information is available mere
centimetres away, so including it again is redundant. Where's the
benefit?

Redundancy is the enemy of information density (to steal Eric's
phrase). You want to get as much information across to the reader with
the least about of fluff - which is one argument in favour of
object/collection initializers too, on a somewhat separate note.

Getting the same amount of information just as clearly across without
repeating yourself is a good thing.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk


Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.