That can be silly question but I really don't know the reason.
// i is compiled as an int
var i = 5;
// s is compiled as a string
var s = "Hello";
// a is compiled as int[]
var a = new[] { 0, 1, 2 };
// expr is compiled as IEnumerable<Customer>
// or perhaps IQueryable<Customer>
var expr =
from c in customers
where c.City == "London"
select c;
// anon is compiled as an anonymous type
var anon = new { Name = "Terry", Age = 34 };
// list is compiled as List<int>
var list = new List<int>();
If so, why C#
needs integral types like int
, string
, int[]
, List&l开发者_JAVA技巧t;>
? If we can do that only with var
keywords, why are there integral types?
Another way,
What is the difference between these ?
var s = "Hello";
string s = "Hello";
in no particular order...
var
is only a compiler construct; evenvar i = 4;
is typed asint
- C# hasn't always had
var
, and you can't remove keywords without utterly breaking existing code. - you can only use var in method variables - not fields, parameters, return types etc.
- most people are happy to type
int
in place of var! Especially when the type matters and there are bytes, floats, enums, decimals etc that all work with the literal0
; i.e.short x = 0; int y = 0; long z = 0;
- why change onlyint
tovar
there? - you can't use
var
to specify a generic type parameter (<T>
) or in atypeof
- you can't use
var.TryParse
in place ofint.TryParse
Many people would argue that it is better practice to write int i = 5
rather than var i = 5
. There are many reasons for this, but the most compelling to me is that I can look at the code and know immediately, without stretching my brain, what type i
is. This allows my brain to concentrate on the harder problems.
In fact var
was introduced to declare variables whose types could not easily be named. It was not introduced as a convenience, although it can be used that way.
The var
keyword is just syntactic sugar, which can only be used for local variables in methods. It's still a strongly typed variable. You can hover the mouse over it in visual studio to see what type it is.
We still need types as otherwise how would you do var list = new List<int>();
? You need to type List<int>
somewhere!
In many cases its best to be explicit, for example when working with literals that could be a number of different types, or to increase readability.
There is no difference between var s = "Hello";"
and string s ="Hello";"
. However, there's a big difference between var foo = new Foo();
and IFoo foo = new Foo();
. In the first case all of Foo's members are accessible, in the latter it's ensured that only interface members is used. This may be important to ensure that the behavior is compatible with the interface, not only the concrete implementations.
Also, var
can't be used to pass function arguments or to declare member variables. As of to use or not to use var
, I refer to this question.
精彩评论