Task 3 – Using var to create more concise code
Implicitly typed variables become very useful as the type of the initialization expression becomes more complicated; in particular, when instantiating a complex generic type. In this task, you will return to the Main method and show how var is used to create more concise code: 1. In Main, replace the type of customers with var: static void Main(string[] args) { var customers = CreateCustomers();
Console.WriteLine("Customers:\n"); foreach (Customer c in customers) Console.WriteLine(c); }
2. Press Ctrl+F5 to run the application and print the customers. After viewing the results, press any key to terminate the application. 3. Now replace the type in the foreach statement with var. static void Main(string[] args) { var customers = CreateCustomers();
Console.WriteLine("Customers:\n"); foreach (var c in customers) Console.WriteLine(c); }
4. Press Ctrl+F5 to run the application and see the same output. Then press any key to terminate the application.
In this task the var keyword was used to infer the type of the foreach local variable is Customer in the foreach loop. This is generally applicable for use in foreach. var was also used to replace the types of the objects returned from the method call. The current function of Main is to retrieve data from a method and print the data. In this respect the type of information that is returned does not matter. Notice no type is specified in Main. Especially for longer and more complex types, using implicitly typed local variable declarations simplify the variable declarations, reducing the amount of code required and the associated coding errors. This is also true when the type is unnamed or unspecified as shown in Exercises 7 (Queries) and 8 (Anonymous Types).
|