views:

148

answers:

3

Look please below what is the difference between two type of codes. is there any performance difference or what else?

First Codes



                ObjectQuery departmans = staffContext.Departman;
                GridView1.DataSource = departmans;
                GridView1.DataBind();

Second Codes

var departmans = staffContext.Departman;
   GridView1.DataSource = departmans;
                GridView1.DataBind();

Thanks

+3  A: 

The effective difference in the outputted code depends on the type of Departman. If the type of Departman is ObjectQuery then the code is equivalent.

The "var" keyword simply tells the compiler, please set the type of this variable to the same type as the expression assigning to it. In this case, it's the type of Departman.

JaredPar
+2  A: 

There is no difference (assuming the type of staffContext.Departman is ObjectQuery and not some sub class of ObjectQuery). The compiler just infers the type based on the right-hand side of the assignment.

Jonathan
+1  A: 

The type that the var keyword represents has to be known at compile time, so as long as the type actually is the same in both cases the executable code will be identical.

The type is inferred based on the type of the right hand side, so in some cases you need to specify the type to get the result that you want. For example:

Stream s = File.OpenRead(fileName);

This will of course give you a variable of the type Stream. On the other hand:

var s = File.OpenRead(fileName);

This will instead give you a variable of the type FileStream.

As a general rule, if the type on the right hand side isn't obvious, you should not use the var keyword at all.

Guffa