Chapter 1: Creating Your First C# Console Application
In This Chapter
Getting a quick introduction to programming
Creating a simple console application
Examining the console application
Saving code for later
In this chapter, I explain a little bit about computers, computer languages — including the computer language C# (pronounced “see sharp”) — and Visual Studio 2012. Then I take you through the steps for creating a simple program written in C#.
Getting a Handle on Computer Languages, C#, and .NET
A computer is an amazingly fast but incredibly stupid servant. Computers will do anything you ask them to (within reason); they do it extremely fast — and they’re getting faster all the time.
Unfortunately, computers don’t understand anything that resembles a human language. Oh, you may come back at me and say something like, “Hey, my telephone lets me dial my friend by just speaking his name. I know that a tiny computer runs my telephone. So that computer speaks English.” But that’s a computer program that understands English, not the computer itself.
The language that computers truly understand is machine language. It’s possible, but extremely difficult and error-prone, for humans to write machine language.
Humans and computers have decided to meet somewhere in the middle. Programmers create programs in a language that isn’t nearly as free as human speech, but it’s a lot more flexible and easy to use than machine language. The languages occupying this middle ground — C#, for example — are high-level computer languages. (High is a relative term here.)
What’s a program?
What is a program? In a practical sense, a Windows program is an executable file that you can run by double-clicking its icon. For example, the version of Microsoft Word that I’m using to write this book is a program. You call that an executable program, or executable for short. The names of executable program files generally end with the extension .exe
. Word, for example, is Winword.exe
.
But a program is something else, as well. An executable program consists of one or more source files. A C# source file, for instance, is a text file that contains a sequence of C# commands, which fit together according to the laws of C# grammar. This file is known as a source file, probably because it’s a source of frustration and anxiety.
Uh, grammar? There’s going to be grammar? Just the C# kind, which is much easier than the kind most people struggled with in junior high school.
What’s C#?
The C# programming language is one of those intermediate languages that programmers use to create executable programs. C# combines the range of the powerful but complicated C++ (pronounced “see plus plus”) with the ease of use of the friendly but more verbose Visual Basic. (Visual Basic’s newer .NET incarnation is almost on par with C# in most respects. As the flagship language of .NET, C# tends to introduce most new features first.) A C# program file carries the extension .cs
.
Some wags have pointed out that C-sharp and D-flat are the same note, but you shouldn’t refer to this new language as “D-flat” within earshot of Redmond, Washington.
C# is
Flexible: C# programs can execute on the current machine, or they can be transmitted over the web and executed on some distant computer.
Powerful: C# has essentially the same command set as C++ but with the rough edges filed smooth.
Easier to use: C# error-proofs the commands responsible for most C++ errors, so you spend far less time chasing down those errors.
Visually oriented: The .NET code library that C# uses for many of its capabilities provides the help needed to readily create complicated display frames with drop-down lists, tabbed windows, grouped buttons, scroll bars, and background images, to name just a few.
Internet-friendly: C# plays a pivotal role in the .NET Framework, Microsoft’s current approach to programming for Windows, the Internet, and beyond.
.NET is pronounced “dot net.”
Secure: Any language intended for use on the Internet must include serious security to protect against malevolent hackers.
Finally, C# is an integral part of .NET.
What’s .NET?
.NET began several years ago as Microsoft’s strategy to open up the web to mere mortals like you and me. Today, it’s bigger than that, encompassing everything Microsoft does. In particular, it’s the new way to program for Windows. It also gives a C-based language, C#, the simple, visual tools that made Visual Basic so popular.
A little background helps you see the roots of C# and .NET. Internet programming was traditionally very difficult in older languages such as C and C++. Sun Microsystems responded to that problem by creating the Java programming language. To create Java, Sun took the grammar of C++, made it a lot more user-friendly, and centered it around distributed development.
When Microsoft licensed Java some years ago, it ran into legal difficulties with Sun over changes it wanted to make to the language. As a result, Microsoft more or less gave up on Java and started looking for ways to compete with it.
Being forced out of Java was just as well because Java has a serious problem: Although Java is a capable language, you pretty much have to write your entire program in Java to get the full benefit. Microsoft had too many developers and too many millions of lines of existing source code, so Microsoft had to come up with some way to support multiple languages. Enter .NET.
.NET is a framework, in many ways similar to Java’s libraries — and the C# language is highly similar to the Java language. Just as Java is both the language itself and its extensive code library, C# is really much more than just the keywords and syntax of the C# language. It’s those things empowered by a well-organized library containing thousands of code elements that simplify doing about any kind of programming you can imagine, from web-based databases to cryptography to the humble Windows dialog box.
Microsoft would claim that .NET is much superior to Sun’s suite of web tools based on Java, but that’s not the point. Unlike Java, .NET doesn’t require you to rewrite existing programs. A Visual Basic programmer can add just a few lines to make an existing program web-knowledgeable (meaning that it knows how to get data off the Internet). .NET supports all the common Microsoft languages — and hundreds of other languages written by third-party vendors. However, C# is the flagship language of the .NET fleet. C# is always the first language to access every new feature of .NET.
What is Visual Studio 2012? What about Visual C#?
(You sure ask lots of questions.) The first “Visual” language from Microsoft was Visual Basic. The first popular C-based language from Microsoft was Visual C++. Like Visual Basic, it had Visual in its name because it had a built-in graphical user interface (GUI — pronounced “GOO-ee”). This GUI included everything you needed to develop nifty-gifty C++ programs.
Eventually, Microsoft rolled all its languages into a single environment — Visual Studio. As Visual Studio 6.0 started getting a little long in the tooth, developers anxiously awaited version 7. Shortly before its release, however, Microsoft decided to rename it Visual Studio .NET to highlight this new environment’s relationship to .NET.
That sounded like a marketing ploy to me — until I started delving into it. Visual Studio .NET differed quite a bit from its predecessors — enough to warrant a new name. Visual Studio 2012 is the sixth-generation successor to the original Visual Studio .NET. (Book IV is full of Visual Studio goodness, including instructions for customizing it.)
Okay, that’s it. No more questions. (For now, anyway.)
Creating Your First Console Application
Visual Studio 2012 includes an Application Wizard that builds template programs and saves you a lot of the dirty work you’d have to do if you did everything from scratch. (I don’t recommend the from-scratch approach.)
Typically, starter programs don’t really do anything — at least, not anything useful. (Sounds like most of my programs.) However, they do get you beyond that initial hurdle of getting started. Some starter programs are reasonably sophisticated. In fact, you’ll be amazed at how much capability the App Wizard can build on its own, especially for graphical programs.
This starter program isn’t even a graphical program, though. A console application is one that runs in the “console” within Windows, usually referred to as the DOS prompt or command window. If you press Ctrl+R and then type cmd
, you see a command window. It’s the console where the application will run.
Creating the source program
To start Visual Studio, press the Windows button on your keyboard and type Visual Studio. Visual Studio 2012 appears as one of the available options.
Complete these steps to create your C# console app:
1. Open Visual Studio 2012 and click the New Project link, shown in Figure 1-1.
Figure 1-1: Creating a new project starts you down the road to a better Windows application.
Visual Studio presents you with lots of icons representing the different types of applications you can create, as shown in Figure 1-2.
Figure 1-2: The Visual Studio App Wizard is eager to create a new program for you.
2. In this New Project window, click the Console Application icon.
Make sure that you select Visual C# — and under it, Windows — in the Project Types pane; otherwise Visual Studio may create something awful like a Visual Basic or Visual C++ application. Then click the Console Application icon in the Templates pane.
Visual Studio requires you to create a project before you can start entering your C# program. A project is a folder in which you throw all the files that go into making your program. It has a set of configuration files that help the compiler do its work. When you tell your compiler to build (compile) the program, it sorts through the project to find the files it needs in order to re-create the executable program.
3. The default name for your first application is ConsoleApplication1
, but change it this time to Program1 by typing in the Name field.
The default place to store this file is somewhere deep in your Documents
directory. Maybe because I’m difficult (or maybe because I’m writing a book), I like to put my programs where I want them to go, not necessarily where Visual Studio wants them. To simplify working with this book, you can change the default program location. Follow these steps to make that happen:
a. Choose Tools⇒Options.
The Options dialog box opens. You may have to check the Show All Options box.
b. Choose Projects and Solutions⇒General.
c. Select the new location in the Projects Location field and click OK.
(I recommend C:C#Programs
for this book.)
You can create the new directory in the Projects Location dialog box at the same time. Click the folder icon with a small sunburst at the top of the dialog box. (The directory may already exist if you’ve installed the example programs from the website.)
You can see the Options dialog box in Figure 1-3. Leave the other fields in the project settings alone for now. Read more about customization of Visual Studio in Book IV.
Figure 1-3: Changing the default project location.
4. Click the OK button.
After a bit of disk whirring and chattering, Visual Studio generates a file named Program.cs
. (If you look in the window labeled Solution Explorer, you see some other files; ignore them for now. If Solution Explorer isn’t visible, choose View⇒Solution Explorer.)
C# source files carry the extension .cs
. The name Program
is the default name assigned for the program file.
The contents of your first console app appear this way:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program1
{
class Program
{
static void Main(string[] args)
{
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Regions help you focus on the code you’re working on by hiding code that you aren’t. Certain blocks of code — such as the namespace
block, class
block, methods, and other code items — get a +/– automatically without a #region
directive. You can add your own collapsible regions, if you like, by typing #region
above a code section and #endregion
after it. It helps to supply a name for the region, such as Public methods
. This code section looks like this:
#region Public methods
... your code
#endregion Public methods
For now, using System;
is the only using
directive you really need. You can delete the others; the compiler lets you know whether you’re missing one.
Taking it out for a test drive
To convert your C# program into an executable program, choose Build⇒Build Program1. Visual Studio responds with the following message:
- Build started: Project: Program1, Configuration: Debug Any CPU -
Csc.exe /noconfig /nowarn ... (and much more)
Compile complete -- 0 errors, 0 warnings
Program1 -> C:C#Programs ... (and more)==Build: 1 succeeded or up-to-date, 0 failed, 0 skipped==
The key point here is the 1 succeeded
part on the last line.
To execute the program, choose Debug⇒Start. The program brings up a black console window and terminates immediately. (If you have a fast computer, the appearance of this window is just a flash on the screen.) The program has seemingly done nothing. In fact, this is the case. The template is nothing but an empty shell.
Making Your Console App Do Something
using System;
namespace Program1
{
public class Program
{
// This is where your program starts.
static void Main(string[] args)
{
// Prompt user to enter a name.
Console.WriteLine(“Enter your name, please:”);
// Now read the name entered.
string name = Console.ReadLine();
// Greet the user with the name that was entered.
Console.WriteLine(“Hello, “ + name);
// Wait for user to acknowledge the results.
Console.WriteLine(“Press Enter to terminate...”);
Console.Read();
}
}
}
Choose Build⇒Build Program1 to convert this new version of Program.cs
into the Program1.exe
program.
From within Visual Studio 2012, choose Debug⇒Start Without Debugging. The black console window appears and prompts you for your name. (You may need to activate the console window by clicking it.) Then the window shows Hello
, followed by the name entered, and displays Press Enter to terminate . . .
. Pressing Enter closes the window.
CD C#ProgramsProgram1inDebug
Now enter Program1 to execute the program. The output should be identical to what you saw earlier. You can also navigate to the C#ProgramsProgram1inDebug
folder in Windows Explorer and then double-click the Program1.exe
file.
Reviewing Your Console Application
In the following sections, you take this first C# console app apart one section at a time to understand how it works.
The program framework
The basic framework for all console applications starts as the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program1
{
public class Program
{
// This is where your program starts.
public static void Main(string[] args)
{
// Your code goes here.
}
}
}
The program starts executing right after the statement containing Main()
and ends at the closed curly brace (}
) following Main()
. (I explain the meaning of these statements in due course. More than that, I cannot say for now.)
Comments
The template already has lots of lines, and I’ve added several other lines, such as the following (in boldface):
// This is where your program starts.
public static void Main(string[] args)
C# ignores the first line in this example. This line is known as a comment.
Why include lines if the computer ignores them? Because comments explain your C# statements. A program, even in C#, isn’t easy to understand. Remember that a programming language is a compromise between what computers understand and what humans understand. These comments are useful while you write the code, and they’re especially helpful to the poor sap — possibly you — who tries to re-create your logic a year later. Comments make the job much easier.
The meat of the program
The real core of this program is embedded within the block of code marked with Main()
, like this:
// Prompt user to enter a name.
Console.WriteLine(“Enter your name, please:”);
// Now read the name entered.
string name = Console.ReadLine();
// Greet the user with the name that was entered.
Console.WriteLine(“Hello, “ + name);
The program begins executing with the first C# statement: Console.WriteLine
. This command writes the character string Enter your name, please:
to the console.
The next statement reads in the user’s answer and stores it in a variable (a kind of workbox) named name
. (See Chapter 2 of this minibook for more on these storage locations.) The last line combines the string Hello,
with the user’s name and outputs the result to the console.
The final three lines cause the computer to wait for the user to press Enter before proceeding. These lines ensure that the user has time to read the output before the program continues:
// Wait for user to acknowledge the results.
Console.WriteLine(“Press Enter to terminate...”);
Console.Read();
This step can be important, depending on how you execute the program and depending on the environment. In particular, running your console app inside Visual Studio, or from Windows Explorer, makes the preceding lines necessary — otherwise, the console window closes so fast you can’t read the output. If you open a console window and run the program from there, the window stays open regardless.
Introducing the Toolbox Trick
The key part of the program you create in the preceding section consists of the final two lines of code:
// Wait for user to acknowledge the results.
Console.WriteLine(“Press Enter to terminate...”);
Console.Read();
The easiest way to re-create those key lines in each future console application you write is described in the following sections.
Saving code in the Toolbox
The first step is to save those lines in a handy location for future use: the Toolbox window. With your Program1
console application open in Visual Studio, follow these steps:
1. In the Main()
method of class Program
, select the lines you want to save — in this case, the three lines mentioned previously.
2. Make sure the Toolbox window is open on the left. (If it isn’t, open it by choosing View⇒Toolbox.)
3. Drag the selected lines into the General tab of the Toolbox window and drop them. (Or copy the lines and paste them into the Toolbox.)
The Toolbox stores the lines there for you in perpetuity. Figure 1-4 shows the lines placed in the Toolbox.
Figure 1-4: Setting up the Toolbox with some handy saved text for future use.
Reusing code from the Toolbox
Now that you have your template text stored in the Toolbox, you can reuse it in all console applications you write henceforth. Here’s how to use it:
1. In Visual Studio, create a new console application as described in the section “Creating the source program,” earlier in this chapter.
2. Click in the editor at the spot where you’d like to insert some Toolbox text.
3. With the Program.cs
file open for editing, make sure the Toolbox window is open.
If it isn’t, see the procedure in Saving Code in the Toolbox, above.
4. In the General tab of the Toolbox window (other tabs may be showing), find the saved text you want to use and double-click it.
The selected item is inserted at the insertion point in the editor window.
With that boilerplate text in place, you can write the rest of your application above those lines. That’s it. You now have a finished console app. Try it out for about 30 seconds. Then you can check out Chapter 2 of this minibook.