Free mag vol1 | Page 174

CHAPTER 3  CORE C# PROGRAMMING CONSTRUCTS, PART I  Source Code The TypeConversions project is located under the Chapter 3 subdirectory. Understanding Implicitly Typed Local Variables Up until this point in the chapter, when we have been defining local variables, we’ve explicitly specified the underlying data type of each variable being declared. static void DeclareExplicitVars() { // Explicitly typed local variables // are declared as follows: // dataType variableName = initialValue; int myInt = 0; bool myBool = true; string myString = "Time, marches on..."; } While many (including yours truly) would argue that is it is always good practice to explicitly specify the data type of each variable, the C# language does provide for implicitly typing of local variables using the var keyword. The var keyword can be used in place of specifying a specific data type (such as int, bool, or string). When you do so, the compiler will automatically infer the underlying data type based on the initial value used to initialize the local data point. To illustrate the role of implicit typing, create a new Console Application project named ImplicitlyTypedLocalVars. Notice how the local variables within the previous method can now be declared as follows: static void DeclareImplicitVars() { // Implicitly typed local variables // are declared as follows: // var variableName = initialValue; var myInt = 0; var myBool = true; var myString = "Time, marches on..."; }  Note Strictly speaking, var is not a C# keyword. It is permissible to declare variables, parameters, and fields named “var” without compile-time errors. However, when the var token is used as a data type, it is contextually treated as a keyword by the compiler. In this case, the compiler is able to infer, given the initially assigned value, that myInt is, in fact, a System.Int32, myBool is a System.Boolean, and myString is indeed of type System.String. You can verify this by printing out the type name via reflection. As you will see in much more detail in Chapter 15, reflection is the act of determining the composition of a type at runtime. For example, using reflection, 108