varType "var" is commonly used in C#, but do not confuse var with the concept of a VB variant (it's not), nor with the concept of var in dynamic languages like JavaScript (where var really means object).

In these languages the variable's type can change, and so type checking is performed at run-time increased flexibility at the cost of safety.

In C# 3.0 the type cannot change, and all type checking is done at compile-time.

For example, if the inferred type is object (as for obj6 below), in C# 3.0 you end up with an object reference of very little functionality:

   object obj5 = "hi";  // obj5 references the string "hi!", but type is object
   var    obj6 = obj5;  // obj6 also references "hi!", with inferred type object

   string s1 = obj6.ToUpper();  // ERROR: 'object' does not contain 'ToUpper'
posted on 2011-08-05 07:55  lochker  阅读(285)  评论(0编辑  收藏  举报