October 19, 2012

Declare var Globally

On different forums, many peoples are asking about the same thing like:

string a; (This is valid no issue)
var a; (This is error why??)

So my answer to them are that the following restrictions apply to implicitly-typed variable declarations like var
  • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
  • var cannot be used on fields at class scope.
  • Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.
If you want to use var, then the compiler MUST know at compile time what the type will be. Let me give you an another example

string myString; (At compile time, compiler knows what type myString is)
var myString;  (At compile time, compiler does not know what the type myString is)

Let me fix it using explicit type as like this :

var myString = "default value";  (Valid, because the value on the right hand side of the '=' is a string)

No comments:

Post a Comment