Now that you've been introduced to the most basic C# program, it's time to declare a local variable. Once a variable is declared, you can assign it a value, replace that value with a new value, and use it in calculations, output, and so on. However, you cannot change the data type of the variable. In Listing 1.9, string max is a variable declaration. Listing 1.9. Declaring and Assigning a Variable
Data TypesListing 1.9 declares a variable with the data type string. Other common data types used in this chapter are int and char.
The next chapter looks at these and other common data types in more detail.
Declaring a VariableIn Listing 1.9, string max is a variable declaration of a string type whose name is max. It is possible to declare multiple variables within the same statement by specifying the data type once and separating each identifier with a comma. Listing 1.10 demonstrates this. Listing 1.10. Declaring Two Variables within One Statement
Because a multivariable declaration statement allows developers to provide the data type only once within a declaration, all variables will be of the same type. In C#, the name of the variable may begin with any letter or an underscore (_), followed by any number of letters, numbers, and/or underscores. By convention, however, local variable names are camel cased (the first letter in each word is capitalized, except for the first word) and do not include underscores. Assigning a VariableAfter declaring a local variable, you must assign it a value before referencing it. One way to do this is to use the = operator, also known as the simple assignment operator. Operators are symbols used to identify the function the code is to perform. Listing 1.11 demonstrates how to use the assignment operator to designate the string values to which the variables max [1.7] and valerie will point.
Listing 1.11. Changing the Value of a Variable
From this listing, observe that it is possible to assign a variable as part of the variable declaration (as it was for max), or afterward in a separate statement (as with the variable valerie). The value assigned must always be on the right side. Running the compiled MiracleMax.exe program produces the code shown in Output 1.3. Output 1.3.
C# requires that developers assign a local variable before accessing it. Additionally, an assignment returns a value. Therefore, C# allows multiple assignments within the same statement, as demonstrated in Listing 1.12. Listing 1.12. Assignment Returning a Value That Can Be Assigned Again
Using a VariableThe result of the assignment, of course, is that you can then refer to the value using the variable identifier. Therefore, when you use the variable max within the System.Console.WriteLine(max) statement, the program displays Have fun storming the castle!, the value of max, on the console. Changing the value of max and executing the same System.Console.WriteLine(max) statement causes the new max value, It would take a miracle., to be displayed.
|