In this chapter we'll walk through how to create a new project, and then output (write out) text to the console window. At the end of this section you'll replace the example text with your own.
New Project
Launch Visual Studio. Like many applications, Visual Studio has several ways to perform common operations (such as starting a new project). Which you choose is your preference.
- Select the option from the Start Page (see screenshot on the left)
- OR choose the File drop down menu (top left of the application) and select File > New > Project...
- OR use the keyboard shortcut Ctrl-Shift-N
New Project Dialog Box
The New Project dialog box has options for the project, such as where files will be saved, and the project name. There are three places for you to make changes for your Adventure Game (highlighted in the screenshot below):
- Language: On the left side of the dialog box choose Visual C#. As you can see from the list, Visual Studio supports development with other languages besides C#. It is important to choose the correct language for template and project setup.
- Template: In the middle pane choose Console Application. Visual Studio will create a project skeleton for a command-line application.
- Project name: Name your project something like 'Adventure' or 'AdventureGame'. Keep your project name as one word - no spaces.
Before you click OK look at the location address underneath the project name. This is where Visual Studio will be saving files for our project. (In later chapters we'll need to navigate to this folder so it is a good idea for you to know where Visual Studio is saving your files at.)
Click OK to close the dialog box.
Visual Studio Generated Code
Visual Studio should open up your new project with a code file displayed. On the tab is the file’s name: 'Program.cs'; the default name for the first file in a C# application. The extension .cs indicates it is a C# code file. (If your file has a different extension you might have chosen a language other than C#.)
Window Layout
The way your code and other panes are shown in Visual Studio can be customized.
Your layout probably has a large pane to show code files that takes up most of the layout, an Output pane on the bottom, and the Solution Explorer and Properties on the right. If you modify your layout you can save it as a preset.
If you want to reset the layout to the default you can access it via the Window menu. Window > Reset Window Layout.
Solution Explorer
The Solution Explorer shows files that are part of your project. Not all of your code has to be in one file, and there are several other files that Visual Studio has created to support your project.
If the Solution Explorer is not visible you can open it by using the shortcut Ctrl-Alt-L or by using the View menu (View > Solution Explorer).
If you accidentally close your Program.cs file, or if you reopen your project in the future and your code isn't showing, right click on the file's title in the Solution Explorer and you will see an option to show the code.
Like other large applications, there is a lot of depth to Visual Studio. This series will cover the basics of the IDE needed to build our Adventure Game, but if you want to learn more about it there are plenty of resources available. Click the toggle box below to show resource suggestions.
Visual Studio Resource Recommendations
Text: Professional Visual Studio 2015 by Bruce Johnson (ISBN-13: 978-1119068051). I have the 2012, 2013, and now the 2015 version of this text and I recommend it as a comprehensive guide to Visual Studio. It's big - 1320 pages - and is worth reading if you plan on heavily using Visual Studio.
Online: Microsoft's Developer Network (MSDN) has some helpful resources:
Generated Code
Inside your Program.cs file you can see code that Visual Studio has generated. It should look similar to this:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Adventure { class Program { static void Main(string[] args) { } } }
We'll start with adding some lines of code and testing our application to see it run, then in the next chapter we'll walk through the code to learn what it does.
Do you have a different "namespace" name?
By default Visual Studio will make the namespace name the same as what you named your project, but you can change it to match the example code (Adventure) if you like, or leave it as is.
Until we add more .cs files to our project we don't need to worry about the namespace name for our project. It is okay if your namespace's name is different from the code examples.
namespace Adventure
A namespace is a way of organizing your code (we'll talk more about what namespaces are and why they are useful in the next section).
Quick Quiz
Before we continue, let's check what you remember. These questions should be easy for you!
What language are we using to build our Adventure Game?
Yes! We are using C# (pronounced 'c sharp').
The language we are using is C# (pronounced 'c sharp').
What type of application are we building?
Output: Game Title
To show text for the player to read in the Console Window, we need to add some code. Inside of the Main function add the two lines of code below.
Console.WriteLine("Adventure Game!"); Console.ReadKey();
Console.Read, Console.ReadKey, Console.ReadLine
In our code above if we left out the line Console.ReadKey(), our application would open, run the statement to print out Adventure Game! to the screen, and then close. It would do exactly what we've asked of it. But it would close so quickly we wouldn't have time to read the text in the window!
We are using Console.ReadKey() to keep the application window from closing immediately.
There are three common options for reading in input:
- Console.Read()
- Console.ReadKey()
- Console.ReadLine()
All three of the above will keep the application window open while waiting for input. In the next chapter we'll look at specific differences between these options.
Until you are comfortable with programming, it is better if you type out the lines of code yourself instead of using copy and paste edit options.
Some keyboard shortcuts and IntelliSense drop down menus will write common code elements for you, but typing will help you memorize keywords, and you will have a better sense of the syntax.
IntelliSense menus
When typing code in Visual Studio a drop down menu appears with suggestions based on what you are writing.
You can use arrow keys to move between the options, or the scroll bar on the drop down. Hovering your cursor over one of the items will display information about it. Double-clicking an option, or selecting one and pressing enter, will insert it into your code.
The Intellisense menu is helpful to see what the options are for an element and can speed up development.
Your code should now look something like this:
It is important to make sure that your code is inside the correct set of curly braces (the squiggly brackets { }).
The text inside the quote marks that says Adventure Game! can be your own unique title.
Nested Elements
The curly braces signal the beginning and ending of code blocks. A nested code block is one that opens and closes within another code block.
In the screenshot below, the nested blocks are highlighted. There are three.
- Adventure contains Program.
- Program contains Main.
- Main contains two statements.
Improper Nesting
"Improperly nested" means that an element is not enclosed within curly braces correctly. For example, if an element opened with a left curly brace but did not have a closing counterpart.
This is an easy error for an IDE to detect and alert you about, but sometimes it is difficult to figure out where the problem is. Your IDE might point to a problem at the end of the file, but the missing brace could be much earlier in the code. There are several techniques you can use to help figure out where the problem is.
First, if your IDE has collapsible areas, you can close them and visually see where the IDE thinks your blocks start and end.
Look at the next two Visual Studio screenshots. You can see that on line 11 there is a box with a minus sign. Clicking on that collapses the code block and hides the nested elements.
Above, none of the code blocks are collapsed. Below, the code block that starts on line 11 has been collapsed, and the elements nested inside have been hidden.
Improper Nesting Example
Can you find the error in the code below?
namespace Adventure { class Program { static void Main(string[] args) { Console.WriteLine("Adventure Game!"); Console.ReadKey(); } }
If your IDE doesn’t have collapsable code blocks, or you are using a text editor, you can visually match up the opening curly brace to its closing counterpart. If you follow the C# coding convention to have curly braces on their own line , it might be easier to see where one is missing. Once you know what to look for, a missing brace is usually not that hard to find.
Some text editors automatically draw dotted lines between braces in your code (such as Sublime Text), which makes finding a missing brace easier.
Have you spotted the error, and thought of a way to fix it?
On the line following "static void Main(string[] args)", there is a curly brace that opens a code block, but it doesn’t have a closing counterpart. To fix this error, we would add a brace to the line after “Console.ReadKey();”. See the screenshot below for an example of how the code should look.
Testing the Code
Once you have the code in place, test your program. Press the start button or use the F5 key on your keyboard.
If there are no errors, you should see a console window pop up that looks something like this:
If you have an error, expand the toggle box "Troubleshooting Errors" (below).
Once you see that your application is running, close the console window. There are a couple ways to close it. You can click the red square (where the Start button was).
You can also click the x in the upper right corner of the window.
If you try to add more code to your project when the console window is open, you'll see a reminder that you need to close your application before you can edit it further.
Hopefully everything worked and there were no errors!
Troubleshooting Errors
If you had an error, make sure that your lines of code match the example. Something as simple as a missing semicolon or a parenthesis can keep your application from running.
Your code needs to be properly nested. This means that it is inside the correct code block, or set of {} curly braces. If the lines of code are not inside the curly braces for the Main() function (as shown in the screenshot) an error might occur.
To Undo a change you can use Ctrl-Z or the Edit menu (Edit > Undo).
Still Not Working?
If you are stuck and you can't get your code to run, try replacing what is in your Program.cs file with this example code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Adventure { class Program { static void Main(string[] args) { Console.WriteLine("Adventure Game!"); Console.Read(); } } }
- Copy the above code. The keyboard shortcut for copy is Ctrl-C. You can also use the Edit menu (Edit > Copy).
- In your Program.cs file, select all by using the shortcut Ctrl-A or via the Edit menu with Edit > Select All.
- Next use Ctrl-V (Edit > Paste) to paste the example code over what is currently in your Program.cs file. This should replace everything in the file with the example code.
Try clicking the start button again (or F5) to see if it will run.
Project Files
There are several ways to open a project using Visual Studio. With some of the options, however, it is important to know which file to select. Visual Studio generates a lot of files for you, but not all of them will open a project in a way that will allow you to edit it.
Recent Projects
You can launch from "Recent"; after you've made at least one project, Visual Studio's Start Page will have a Recent section with links to projects. Straightforward and easy, this is a good choice.
File Menu Options
There are also two options in the File drop down menu. The first is Open > Project/Solution (CTRL-SHIFT-O).
When you open a project with this option, choose the Solution file. It has a file extension of .sln.
The File menu also has a choice called "Recent Projects and Solutions".
Remember the .sln file is the one to select.
Project File Types
If you've looked into your project directory, you've probably noticed that Visual Studio has created a lot of folders and files for you.
There are three different types of files you should know about. The first is your .sln file. This will open up your project Solution.
The second is Program.cs. The .cs indicates that the file is C# code. Projects can have more than one .cs file.
If you open a .cs file in Visual Studio you will see your code, but you won't be able to do all of the things you are used to doing when you have a Solution open. Always open the .sln file when you want to work on your project.
The third file extension you should know is .exe. When you test your project (by pressing Play or F5), Visual Studio compiles your code into an executable application. You can double-click on the .exe in your bin > Debug folder and run it. You'll see the last version of your project that Visual Studio has compiled.
Important files to know:
- Solution (.sln): open your project with this file.
- C# Code (.cs): A file with C# code.
- Executable (.exe): An executable application.
To Do: Title and Overview
Assignments
- Change the title of your Adventure Game in your code.
- Add another line of code that writes something else to the screen, like an introduction to the game or welcome message.
- Read Problem Solving in Programming.
Now that you know how to write out text to the screen, change the title of your Adventure Game. You should choose something that is unique - so this game will be your own creation. Keep the text basic for now. You can always add to it or edit it as we move through the series.
After you change the title, add another line (just below the one that writes out your game title) that gives a brief introduction to the game. You can describe the setting, or welcome the player - whatever you'd like (example below).
Make sure that you are just changing the text within the quote marks (" "). The quote marks are important markers for what should be written out to the screen.
Before we finish the series we'll look at how to make the text fit better within the window, and ways in which we can add style to it visually.
Example:
Console.WriteLine("Your game title here!"); Console.WriteLine("Welcome to ..... You will be exploring the fantastic world of ..... "); Console.Read();
After you finish changing the code in your game, read about troubleshooting, debugging, and "stepping" through code in Visual Studio.
You have the first version of your Adventure Game application!
Code Files
Example code for this chapter:
Next Step
Now that we have our first version of the application we'll go through the code and discuss some C# programming concepts.