Implicit
type var
The following restrictions apply to implicitly-typed variable declarations:
In
Visual C#, variables that are declared in the method scope can have
an implicit type var.
You can use the modifier var
to instruct the compiler to infer and assign the type, as given
below:
var iRoll = 23; // int iRoll = 23; var sMessage = "Hello"; // string sMessage = "Hello";
Arrays can also be declared with
implicit typing as given below:
var iNum = new[] { 1, 2, 3, 4 }; // int[] var sStr = new[] { "hello", null, "world" }; // string[] var sJagged = new[] { a, new[] { 5, 6, 7, 8 } }; // single-dimension jagged array
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 iAmt and sMessage:
The following example shows an anonymous type being initialized with two properties called iAmt and sMessage:
var v = new { iAmt = 123, sMessage = "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.
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.
No comments:
Post a Comment