Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C# (http://www.programmingforums.org/forum16.html)
-   -   var vs object (http://www.programmingforums.org/showthread.php?t=15608)

Robocop Apr 13th, 2008 1:17 PM

var vs object
 
Can somebody tell me what's the difference between the 'var' and 'object' keywords in c#?

Jimbo Apr 13th, 2008 1:36 PM

Re: var vs object
 
'object' is a keyword because someone thought it would be cool to have a keyword for the System.Object type. It's the same with 'string' (not to be confused with Object and String respectively, since those are the class names, not keywords).

var is a keyword to denote that the type is whatever the assignment expression returns. It can be re-typed through various assignments too. Take the following:
:

  1. var foo;
  2. foo = new String();
  3. foo = new List<int>();

The compiler will determine the type of foo each time it is assigned to. Works pretty handy for anonymous types too :)

xavier Apr 13th, 2008 11:42 PM

Re: var vs object
 
really ?
From what I've read ,once you go
var foo = "";
... you can never go back :).

In other words foo = new List<int>() - won't work because the language is still strongly typed, and will say can't assign List<> to string .. or something like that.

So the var keyword is a simpler way to declare stuff . so you don't have to go:
List<Dictionnary<int,List<string>>> myWeirdList = new List<Dictionnary<int,List<string>>>();

And useful for anonymous types.

Jimbo Apr 14th, 2008 12:55 AM

Re: var vs object
 
Ah, you're right. I take that back, it's typed only on the first assignment.

Ooble Apr 14th, 2008 1:01 AM

Re: var vs object
 
Phew. I got confused there. I remembered reading about var when they first introduced it to the language, and it looked interesting. Then you told me that C# was actually dynamically typed and it blew my mind. :p


All times are GMT -5. The time now is 9:17 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC