Skip to content

C# Adventure 04: Input

Example with player input

You can read in data and use it without saving, but saving data allows you to use it later and in multiple places. We'll ask the player to input a name for their game character, save that name as a variable's value, then use that variable to write the name back out again.

Variable Declaration

Before we read in data, we'll set up a place to save it to.

Here are our steps:

  1. Declare a variable that will store what the player types.
  2. Write out an instruction for the person to enter a name for their character.
  3. Read in what the person typed and store it as the value for the variable.
  4. Write out a confirmation of the character name.

To declare the variable we will specify the data type, an identifier, and optionally an initial value (initialization).

This particular variable will be a "string", since we will be storing a sequence of Unicode values. We've talked about data types and strings before, so that should be familiar.

string CharacterName;

Since we will be asking our player for a name for their character, let's use CharacterName as our identifier. The identifier in this case is the name we will be giving our variable.

We'll end the line with a semicolon to let the compiler know our statement is complete.

More about IntelliSense menus

When you type the name of a static class, or an instance name, IntelliSense will show the properties and methods that you can use for the class or the instance, even for ones that you create yourself.

IntelliSense shows options for the Console class
IntelliSense shows options for the Console class

In the above image WriteLine is shown with "+ 18 overloads". Overloaded methods can be used in multiple ways because they have several definitions.

Assignment and Initialization

The statement above works, but we can also have an initial value for the character's name, or we can have the initial value be an empty string. Giving a variable an initial value is called initialization.

To give a value to a variable in C# we use the assignment operator: the equal sign (=).

The initial value as an empty string:

string CharacterName = "";

The initial value as a default name:

string CharacterName = "John Doe";

Once we have a variable, we can change its value. Here is an example:

string CharacterName = "John Doe";
CharacterName = "Jane Doe";

If we write out the value of CharacterName to the Console Window, it will now be Jane Doe instead of John Doe as we initialized it to be.

Common Errors

There are two common errors for new programmers to watch out for: accidentally attempting to declare a variable again and unintentionally changing the case of a keyword or identifier.

Declaring vs. Assigning a New Value

Precede the variable name (identifier) with the data type only when declaring a variable. When using the variable later don't include the data type again. If you do, the compiler will assume you are trying to declare a different variable with the same identifier and will show an error.

Example: If we create our variable CharacterName with the value 'John Doe' and then later want to change it to be 'Jane Doe', we would do something like this:

//declare variable and initialize it
string CharacterName = "John Doe";

//change the value
CharacterName= "Jane Doe";

The following example will not compile. The error will be something like "local variable named 'CharacterName' is already defined in this scope".

string CharacterName = "John Doe";
string CharacterName= "Jane Doe"; //this line will trigger an error

Case Sensitive

C# is case sensitive. Keep the capitalization the same when using variable names.

string CharacterName = "John Doe";
Charactername = "Jane Doe"; //this line will trigger an error

This example will cause an error. If you try it, you'll see something similar to "The name 'Charactername' does not exist in the current context". The compiler will think that CharacterName and Charactername are two different entities.

Variable Creation

Add the statement to declare and initialize a variable named CharacterName. Look at the example below; we want to add it right before your game's title is written out to the Console Window.

using System;

namespace Adventure
{
    class Program
    {
        static void Main()
        {
            string CharacterName = "John Doe";

            Console.WriteLine("Game Title");
            Console.WriteLine("Welcome to ...");
            Console.ReadKey();
        }
    }
}

Save and run your application to make sure you don't have any errors.

Variable Declaration Locations

Two considerations for variable declaration placement are coding conventions and scope.

Coding Conventions

It is a common practice to have C# variable declarations at the top of a code block. We'll have ours inside the method Main, right after the opening curly brace.

An example of three variables declared together:

using System;

namespace Adventure
{
    class Program
    {
        static void Main()
        {
            //variable declarations
            string CharacterName = "John Doe";
            string Location = "Starting Area";
            string Companion = "Parrot";

            Console.WriteLine("Game Title");
            Console.WriteLine("Welcome to ...");
            Console.ReadKey();
        }
    }
}

The Main method is the entry point to our application, and the statements inside the method's curly braces {} will run as soon as the application is launched. Later we'll look at adding code to areas aside from Main.

Scope

Scope is the area within your program that an entity can be referenced without using a qualified path to it.

We previously looked at an example of a fully qualified path showing the namespace (System), the class (Console), and finally the method (WriteLine).

System.Console.WriteLine("");

In the example below, what do you think will be written out to the console window when it runs?

using System;

namespace Lunch
{
    class Program
    {
        string Food = "A yummy substance";

        static void Main()
        {
            string Food = "Something that can be eaten";
           
            Console.WriteLine(Food);
            Console.ReadKey();
        }
    }
}

Which of these will it be?

  • A yummy substance
  • Something that can be eaten

If you guessed "Something that can be eaten", you were right!

Even though there are two variables with the same name, they are in different scope areas. Because the command to write out the value of Food is in the same scope as the variable with "Something that can be eaten" as the value, that is what is written out.

If both variables named Food were in the same scope there would be an error because they would both be defined with the same identifier.

using System;

namespace Lunch
{
    class Program
    {
        static void Main()
        {
            string Food = "Something that can be eaten";
            string Food = "A yummy substance"; //this line will cause an error
           
            Console.WriteLine(Food);
            Console.ReadKey();
        }
    }
}

Error example
Error example

If you have an error, compare your code to what is shown above and see if you've missed something like a semicolon or parenthesis. If you are stuck on an error, remember you can "step" through your code (Problem Solving in Programming).

You've declared and initialized a variable in your application!

We've completed the first step, declaring a variable. Now we'll move on to the next step:

  1. Declare a variable that will store what the player types (CharacterName).
  2. Write out an instruction for the person to enter a name for their character.
  3. Read in what the person typed and store it as the value for the variable.
  4. Write out a confirmation of the character name.

Instructions for Player

Add a statement that writes out instructions to the Console Window for the player. You'll probably want to put this new statement above the line that has Console.Read(). Ask the player to enter in a name for their character.

This should be easy since you have some examples of how to write out to the Console Window already in your code!

If you aren't sure how to add the statement you can expand the toggle box below for an example.

Example Code

4.2 Instructions for Player.

using System;

namespace Adventure
{
    class Program
    {
        static void Main()
        {
            string CharacterName = "John Doe";

            Console.WriteLine("Game Title");
            Console.WriteLine("Welcome to ...");
            Console.WriteLine("What would you like your character's name to be?");
           
            Console.ReadKey();
        }
    }
}

Save and run your application to make sure you don't have any errors.

Player Input

Next we will add a statement to read in what the player enters for their character's name.

  1. Declare a variable that will store what the player types.
  2. Write out an instruction for the person to enter a name for their character.
  3. Read in what the person typed and store it as the value for the variable.
  4. Write out a confirmation of the character name.

To "read" in what the player types we will use Console.ReadLine().

Storing Input

We want to store what the player will type in as their name. Think of this as two steps:

  1. Get data from the console window (what the player types).
  2. Store data as a string (as the value of the CharacterName variable).

To "get" what the player types, we will use Console.ReadLine(). It will "read" what is typed in.

We'll assign the value of our CharacterName variable to be the information that the player has typed. To do that, we first write the variable's identifier (CharacterName), then an equal sign, then Console.ReadLine(). This will assign what the person enters as the variable's value.

CharacterName = Console.ReadLine();

Add this statement after the line that asks the player for a name.

Why ReadLine() Instead of Read()?

We've used Console.Read() to keep our Console Window open. Read() reads in from the standard input stream, and a side effect of this is that the Console Window will stay open until something is read in.

Why are we now using Console.ReadLine()?

There are two better methods for reading in input than using Read().

  • Console.ReadLine(): Reads the next line of characters entered.
  • Console.ReadKey(): Obtains the next character entered.

So if you want to read in a name, word, or other string, you should use Console.ReadLine(). If you are only going to read in a single character, you can use Console.ReadKey() but using characters is different than using strings. Since you already know how to work with strings, you might want to stick with Console.ReadLine() for now.

You can use Console.ReadLine() or Console.ReadKey() to keep your Console Window open, too, but remember that keeping the window open is a side effect, it isn't the primary purpose of these methods.

Concatenation

The last step is to write out a confirmation of what the person entered. Use Console.WriteLine() as you have before, but also add the concatenation operator, the plus sign (+), and the name of the variable that we want to print the value from.

Example:

Console.WriteLine("Great! Your character is now named " + CharacterName);

After the word "named" there is a space. If you leave out the space words will run together.

If our player typed in Lily for their name, the following code (without a space) would print out "beLily":

Example of concatenation without space
Example of concatenation without space

However, with a space we see "be Lily":

Example of concatenation with space
Example of concatenation with space

This is one way to write out a variable's value to the Console Window. We concatenate (or link) strings to variable values using the + symbol.

The name is written back out just as it was typed in. If the person entered their name lowercase, then it won't be capitalized when printed back out. We'll look at how to fix this, though, before our Adventure game is finished!

Add your statement to confirm the name the player entered.

Save and test your code to make sure there are no errors.

More about variables

Strongly-Typed Language

C# is a "strongly-typed" language. This means that variables (and some other elements) all have a specific type.

Types

A type has important information for the compiler such as how much storage space a variable of that type needs, and the kinds of operations or actions that are valid for it.

An example of an operation would be using the + symbol between two variables. If the variables are numbers, such as integers, you will get a sum of the two numbers added together. If the variables are strings, they will be concatenated.

int apples = 1;
int oranges = 2;

string breakfast = "cereal";
string dinner = "sandwich";

Console.WriteLine(apples + oranges);
Console.WriteLine(breakfast + dinner);
Console.Read();

Integers and strings act differently when the + operator is used. Running the above code will produce the following written to the console window:

3
cerealsandwich

The number on the first line is the result of 1 + 2.

The second line has two words (two strings) that have been joined together with the + operator.

Implicit Typing

"Implicit typing" is declaring variables without stating the data type; instead the keyword "var" is used. There are some restrictions on when and how implicit typing can be used, and these types of variables need to be initialized with a value.

Instead of stating that the CharacterName variable will be a string:

string CharacterName;

You can alternatively write this:

var CharacterName="";

A value (even an empty string) had to be assigned. Just "var CharacterName;" would raise an error.

Declare your variables for this project with a data type. Explicitly state the data type until you are building advanced projects and have a deeper understanding of the language.

Backup

Keep backup copies of your work as you progress. If you make changes that you don't like, you can "roll back" to a previous version. At each major change (for example, each new chapter of this series) you should consider backing up your project folder. Three suggestions for backing up your work: compressed archive, GitHub, or copy the folder.

Compressed Archive

If you have a file archive program like 7-zip you can easily create a compressed copy of your project folder.

Some archive programs have convenient right-click options
Some archive programs have convenient right-click options

GitHub

There is a free GitHub extension for Visual Studio 2015 if you want a more advanced option. GitHub can host and manage your work, allow you to collaborate more easily with others, and create an online portfolio. If you haven't tried GitHub yet, there is a friendly tutorial at try.github.io.

Folder Copy

If you don't have a file archive program or want to use GitHub, you can make a copy of your project folder and save it in a safe place.

Project Folder Location

If you've forgotten where Visual Studio saves your project folder, you can check the location in the new project dialog box. For example: "c:\users\YourUserName\documents\visual studio 2015\Projects".

Dialog box options (Adventure Game Console)
The path to your project is in the location box

Quick Quiz

The operation of joining things together is called which of the following?

Correct
Incorrect

To declare a variable we need to have a data type, a/an , and optionally an initial value.

Correct
Incorrect

To Do: Practice

Practice what you've learned by making two small applications. The first will build on the previous Hello World walk through by adding user input, and the second will create a Madlib.

Assignments

  1. Back up your project.
  2. Create a Hello World application that takes in player input, then outputs a custom message. Walk through: Hello World 2.0.
  3. Build an application that takes in player input to create a Madlib. Walk through: Simple C# Madlib (Part One).

Code Files

If you have errors, or just want to check how your code compares in terms of progress, the code examples for this chapter are linked below.

Next Step

After you complete the Hello World 2.0 and Madlib walk-throughs, move to the next section where we will look at adding comments and custom functions!