Working with Variables

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.12, string max is a variable declaration.

Listing 1.12: Declaring and Assigning a Variable
public class MiracleMax
    public static void Main()
        string max;     // "string" identifies the data type
                        // "max" is the variable
        max = "Have fun storming the castle!";
Beginner Topic
Local Variables

A variable is a name that refers to a value that can change over time. Local indicates that the programmer declared the variable within a method.

To declare a variable is to define it, which you do by

Specifying the type of data which the variable will contain
Assigning it an identifier (name)
Introducing Data Types

Listing 1.12 declares a variable with the data type string. Other common data types used in this chapter are int and char.

int is the C# designation of an integer type that is 32 bits in size.
char is used for a character type. It is 16 bits, large enough for (nonsurrogate) Unicode characters.

The next chapter looks at these and other common data types in more detail.

Beginner Topic
What Is a Data Type?

The type of data that a variable declaration specifies is called a data type (or object type). A data type, or simply type, is a classification of things that share similar characteristics and behavior. For example, animal is a type. It classifies all things (monkeys, warthogs, and platypuses) that have animal characteristics (multicellular, capacity for locomotion, and so on). Similarly, in programming languages, a type is a definition for several items endowed with similar qualities.

Declaring a Variable

In Listing 1.12, 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.13 demonstrates such a declaration.

Listing 1.13: Declaring Two Variables within One Statement
string message1, message2;

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 camelCased (the first letter in each word is capitalized, except for the first word) and do not include underscores.

DO use camelCasing for local variable names.
Assigning a Variable

After declaring a local variable, you must assign it a value before reading from 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.14 demonstrates how to use the assignment operator to designate the string values to which the variables miracleMax and valerie will point.

Listing 1.14: Changing the Value of a Variable
public class StormingTheCastle
    public static void Main()
        string valerie;
        string miracleMax = "Have fun storming the castle!";
        valerie = "Think it will work?";
        miracleMax = "It would take a miracle.";

From this listing, observe that it is possible to assign a variable as part of the variable declaration (as it was for miracleMax) or afterward in a separate statement (as with the variable valerie). The value assigned must always be on the right side of the declaration.

Running the compiled program produces the code shown in Output 1.3.

Output 1.3
>dotnet run
Have fun storming the castle!
Think it will work?
It would take a miracle.

In this example, we show the command dotnet run explicitly. In future output listings, we will omit this line unless there is something special about the command used to execute the program.

C# requires that local variables be (as determined by the compiler) “definitely assigned” before they are read. Additionally, an assignment results in a value. Therefore, C# allows two assignments within the same statement, as demonstrated in Listing 1.15.

Listing 1.15: Assignment Returning a Value That Can Be Assigned Again
public class StormingTheCastle
    public static void Main()
        // ...
        string requirements, miracleMax;
        requirements = miracleMax = "It would take a miracle.";
        // ...
Using a Variable

The 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 miracleMax within the Console.WriteLine(miracleMax) statement, the program displays “Have fun storming the castle!”—the value of miracleMax—on the console. Changing the value of miracleMax and executing the same Console.WriteLine(miracleMax) statement displays the new miracleMax value, “It would take a miracle.”

AdVanced Topic
Strings Are Immutable

All values of type string, whether string literals or otherwise, are immutable (or unmodifiable). For example, it is not possible to change the string Come As You Are. to Come As You Age. A change such as this requires that you reassign the variable instead of modifying the data to which the variable originally referred.

{{ snackbarMessage }}