Thursday, October 12, 2017

"var" keyword in c#

REF - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var

"var" keyword is given by c# to declare a variable. It can help us avoid writing "type" on LHS of the expression. even though we are not writing type before the variable name, but it does not mean that it doesnt have a type. compiler defines the type by evaluating the RHS of the expression. It is more a implicit type definition.

"var" can not be used at class level to define the fields. if you refer this article -
 https://blogs.msdn.microsoft.com/ericlippert/2009/01/26/why-no-var-on-fields/
It states about compilation process of c# compiler.
First we run through every source file and do a "top level only" parse. That is, we identify every namespace, class, struct, enum, interface, and delegate type declaration at all levels of nesting. We parse all field declarations, method declarations, and so on. In fact, we parse everything except method bodies; those, we skip and come back to them later.
Once we've done that first pass we have enough information to do a full static analysis to determine the type of everything that is not in a method body. We make sure that inheritance hierarchies are acyclic and whatnot. Only once everything is known to be in a consistent, valid state do we then attempt to parse and analyze method bodies. We can then do so with confidence because we know that the type of everything the method might access is well known.
There's a subtlety there. The field declarations have two parts: the type declaration and the initializer. The type declaration that associates a type with the name of the field is analyzed during the initial top-level analysis so that we know the type of every field before method bodies are analyzed. But the initialization is actually treated as part of the constructor; we pretend that the initializations are lines that come before the first line of the appropriate constructor.
So immediately we have one problem; if we have "var" fields then the type of the field cannot be determined until the expression is analyzed, and that happens after we already need to know the type of the field.

Here are the rules with "var" keyword -
- "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.

No comments:

Post a Comment