skip navigation
Previous Next

Strings, types, and variables

You may have noticed in the previous exercise that the only code that was included in the bot's response was between quotes. Like curly braces, a pair of quotes defines a region of code. The region between a pair of quotes is called a string, which is short for a string of characters. A string is a type of data that exists in C# programs. If we want to reuse a piece of data in our code, we can store it in a variable. The key terms here are:

Some information in a program.
In C#, all data has a type. The type of the data defines its use. For example, there is are types for words (string), numbers (int and double), and letters (char).
A piece of memory that can store data. If data is stored in a variable, the data can be referenced later in the code my using the variable.
A type of data that stores a sequence of characters.
A type of data that stores a whole number.

To store a piece of data into a variable, we use this syntax:

<type> <variable name> = <data of the type mentioned>

For example, if we wanted to store the string "Quackers" into a variable named pet, we would write it like this:

string pet = "Quackers";

This line declares a variable named pet with the type string and stores the string "Quackers" inside of it. The advantage of storing data into variables is that later in the program we can use the variable's name to reference the data. For example, assuming that we had already written this line of code earlier in the program, we could return the string "Quackers" with this line of code:

return pet;

Here are some more examples of storing strings into variables:

string lastName = "Smith";
string book = "Second Foundation";
string foo = "blah";

It is important to note that the variable name can be anything you want as long as it does not contain any spaces. You can find additional information on variable types on this reference page.

Previous Next
This work is supported by the following National Science Foundation Grants: CNS-087508, CNS-0549481, IIS-0811884, IIS-0415273
Send comments to Richard Ladner