Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should the var type be used in c#? [duplicate]

Tags:

c#

types

Possible Duplicate:
What’s the point of the var keyword?

What is the var type and should it be used in c#? When should it be used?

Can you specify the var type for the parameters to a method?

like image 523
CJ7 Avatar asked Dec 08 '22 03:12

CJ7


2 Answers

var is not a type. It is a convinient short hand notation that saves you a lot of typing. The following two declarations are equivalent:

Dictionary<string,List<int>> dic = new Dictionary<string,List<int>>();

and

var dic = new Dictionary<string,List<int>>();

As you can see, this saves typing and are easier to read. And if you descide to change the data type, you only have to change the right hand part.

But where I really like it most is in foreach loops:

foreach ( var item in someList )

Here item automatically takes the correct type, depending on the type of someList and it enables you to change the type of someList without haveing to change the declaration of item.

In short: var is GREAT and should be used.

EDIT: No, you can not specify var as a parameter to a function. The closest you can get to that is generics, I guess. And I also completely forgot to mention anonymous types. With those you have to use var.

like image 196
Dan Byström Avatar answered Jan 05 '23 00:01

Dan Byström


It is part of the language, so yes, it should be used. It is not a type, however, but signifies a placeholder for the actual type determined by the compiler.

When should you use it? This has been asked before, many times:

  • Use of var keyword in C#
  • https://stackoverflow.com/questions/633474/c-do-you-use-var
like image 42
Oded Avatar answered Jan 05 '23 00:01

Oded