h1.post-title { color:orange; font-family:verdana,Arial; font-weight:bold; padding-bottom:5px; text-shadow:#64665b 0px 1px 1px; font-size:32px; } -->

Pages

Implicit type var and Anonymous Types

Beginning in Visual C# 3.0, variables that are declared in the method scope can have an implicit type var.  We can use the modifier var to instruct the compiler to infer and assign the type, as shown below:
var i = 23;      // int i = 23;
var s = "Hello"; // string s = "Hello";
Arrays can also be declared with implicit typing as shown below:
var a = new[] { 1, 2, 3, 4 }; // int[]
var b = new[] { "hello", null, "world" }; // string[]
var c = new[] { a, new[] { 5, 6, 7, 8 } }; // single-dimension jagged array

Note: The following restrictions apply to implicitly-typed variable declarations:
  • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null literal, because it does not have a type – like lambda expressions or method groups.  However, it can be initialized with an expression that happens to have the value null, as long as the expression has a type.
  • var cannot be used on fields in class scope.
  • Variables declared by using var cannot be used in their own initialization expression.  
  • In other words, var v = v++; will result in a compile-time error.
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then we will get a compile-time error if we attempt to initialize a local variable with the var keyword.

Anonymous Type
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type.  The type name is generated by the compiler and is not available at the source code level.  The type of the properties is inferred by the compiler.  The following example shows an anonymous type being initialized with two properties called Amount and Message:
var v = new { Amount = 123, Message = "Hello" };
Anonymous types are class types that consist of one or more public read-only properties.   No other kinds of class members such as methods or events are allowed.
Note: Some rules on anonymous types:
  •  You must provide a name to a property that is being initialized with an expression, except in the situation that the second bullet describes.
  • If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the variable, field or property being used to initialize them.    
  • Anonymous types are limited to a local scope.