Home Random Page



Nbsp;   Implicitly Typed Local Variables

C# supports the ability to infer the type of a method’s local variable from the type of expression that is used to initialize it. The following shows some sample code demonstrating the use of this feature.

private static void ImplicitlyTypedLocalVariables() { var name = "Jeff";

ShowVariableType(name); // Displays: System.String


// var n = null; // Error: Cannot assign <null> to an implicitly­typed local variable

var x = (String)null; // OK, but not much value ShowVariableType(x); // Displays: System.String


var numbers = new Int32[] { 1, 2, 3, 4 }; ShowVariableType(numbers); // Displays: System.Int32[]


// Less typing for complex types

var collection = new Dictionary<String, Single>() { { "Grant", 4.0f } };


// Displays: System.Collections.Generic.Dictionary`2[System.String,System.Single] ShowVariableType(collection);


foreach (var item in collection) {

// Displays: System.Collections.Generic.KeyValuePair`2[System.String,System.Single] ShowVariableType(item);




private static void ShowVariableType<T>(T t) { Console.WriteLine(typeof(T));



The first line of code inside the ImplicitlyTypedLocalVariables method is introducing a new local variable by using the C# var token. To determine the type of the name variable, the compiler looks at the type of the expression on the right side of the assignment operator (=). Because "Jeff" is a string, the compiler infers that name’s type must be String. To prove that the compiler is inferring the type correctly, I wrote the ShowVariableType method. This generic method infers the type of its argument, and then it shows the type that it inferred on the console. I added what ShowVariable­

Type displayed as comments inside the ImplicitlyTypedLocalVariables method for easy reading.


The second assignment (commented out) inside the ImplicitlyTypedLocalVariables method would produce a compiler error (error CS0815: Cannot assign <null> to an implicitly­ typed local variable) because null is implicitly castable to any reference type or nullable value type; therefore, the compiler cannot infer a distinct type for it. However, on the third assignment, I show that it is possible to initialize an implicitly typed local variable with null if you explicitly specify a type (String, in my example). Although this is possible, it is not that useful because you could also write String x = null; to get the same result.

In the fourth assignment, you see some real value of using C#’s implicitly typed local variable feat- ure. Without this feature, you’d have to specify Dictionary<String, Single> on both sides of the assignment operator. Not only is this a lot of typing, but if you ever decide to change the collection type or any of the generic parameter types, then you would have to modify your code on both sides of the assignment operator, too.

In the foreach loop, I also use var to have the compiler automatically infer the type of the ele- ments inside the collection. This demonstrates that it is possible and quite useful to use var with foreach, using, and for statements. It can also be useful when experimenting with code. For example, you initialize an implicitly typed local variable from the return type of a method, and as you develop your method, you might decide to change its return type. If you do this, the compiler will automatically figure out that the return type has changed and automatically change the type of the variable! This is great, but of course, other code in the method that uses that variable may no longer compile if the code accesses members by using the variable assuming that it was the old type.

In Microsoft Visual Studio, you can hold the mouse cursor over var in your source code and the editor will display a tooltip showing you the type that the compiler infers from the expression. C#’s implicitly typed local variable feature must be used when working with anonymous types within a method; see Chapter 10, “Properties,” for more details.

You cannot declare a method’s parameter type by using var. The reason for this should be obvi- ous to you because the compiler would have to infer the parameter’s type from the argument being passed at a callsite and there could be no call sites or many call sites. In addition, you cannot declare a type’s field by using var. There are many reasons why C# has this restriction. One reason is that fields can be accessed by several methods and the C# team feels that this contract (the type of the variable) should be stated explicitly. Another reason is that allowing this would permit an anonymous type (discussed in Chapter 10) to leak outside of a single method.



Date: 2016-03-03; view: 1188

<== previous page | next page ==>
Rules and Guidelines | Nbsp;   Passing Parameters by Reference to a Method
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.007 sec.)