Chapter 2. Writing a C# Program

Provided by:   Karli Watson

Beginning Microsoft Visual C# 2008

This topic contains the following sections.

  • The Development Environments
  • Console Applications
  • Windows Forms Applications
  • Summary

Now that you’ve spent some time learning what C# is and how it fits into the .NET Framework, it’s time to get your hands dirty and write some code. You use Visual Studio 2008 (VS) and Visual C# 2008 Express Edition (VCE) throughout this book, so the first thing to do is have a look at some of the basics of these development environments.

VS is an enormous and complicated product, and it can be daunting to first-time users, but using it to create basic applications can be surprisingly simple. As you start to use VS in this chapter, you will see that you don’t need to know a huge amount about it to start playing with C# code. Later in the book you’ll see some of the more complicated operations that VS can perform, but for now a basic working knowledge is all that is required.

VCE is far simpler for getting started, and in the early stages of this book all the examples are described in the context of this IDE. However, if you choose to, you can use VS instead, and everything will work in more or less the same way. For that reason, you’ll see both IDEs in this chapter, starting with VS.

Once you’ve had a look at the IDEs, you put together two simple applications. You don’t need to worry too much about the code in these for now; you just prove that things work. By working through the application creation procedures in these early examples, they will become second nature before too long.

The first application you create is a simple console application. Console applications are those that don’t make use of the graphical windows environment, so you won’t have to worry about buttons, menus, interaction with the mouse pointer, and so on. Instead, you run the application in a command prompt window, and interact with it in a much simpler way.

The second application is a Windows Forms application. The look and feel of this is very familiar to Windows users, and (surprisingly) the application doesn’t require much more effort to create. However, the syntax of the code required is more complicated, even though in many cases you don’t actually have to worry about details.

You use both types of application over the next two parts of the book, with slightly more emphasis on console applications at the beginning. The additional flexibility of Windows applications isn’t necessary when you are learning the C# language, while the simplicity of console applications enables you to concentrate on learning the syntax and not worry about the look and feel of the application.

In this chapter, you learn the following:

  • A basic working knowledge of Visual Studio 2008 and Visual C# 2008 Express Edition.

  • How to write a simple console application.

  • How to write a Windows Form application.

The Development Environments

This section explores the VS and VCE development environments, starting with VS. These environments are similar, and you should read both sections regardless of which IDE you are using.

Visual Studio 2008

When VS is first loaded, it immediately presents you with a host of windows, most of which are empty, along with an array of menu items and toolbar icons. You will be using most of these in the course of this book, and you can rest assured that they will look far more familiar before too long.

If this is the first time you have run VS, you will be presented with a list of preferences intended for users who have experience with previous releases of this development environment. The choices you make here affect a number of things, such as the layout of windows, the way that console windows run, and so on. Therefore, choose Visual C# Development Settings; otherwise, you may find that things don’t quite work as described in this book. Note that the options available vary depending on the options you chose when installing VS, but as long as you chose to install C# this option will be available.

If this isn’t the first time that you’ve run VS but you chose a different option the first time, don’t panic. To reset the settings to Visual C# Development Settings you simply have to import them. To do this, select Tools Import and Export Settings and choose the Reset All Settings option, shown in Figure 2–1.

Beginning Microsoft Visual C# 2008

Figure 2–1

Click Next, and indicate whether you want to save your existing settings before proceeding. If you have customized things, you might want to do this; otherwise, select No and click Next again. From the next dialog, select Visual C# Development Settings, shown in Figure 2–2. Again, the available options may vary.

Beginning Microsoft Visual C# 2008

Figure 2–2

Finally, click Finish to apply the settings.

The VS environment layout is completely customizable, but the default is fine here. With C# Developer Settings selected, it is arranged as shown in Figure 2–3.

Beginning Microsoft Visual C# 2008

Figure 2–3

The main window, which contains a helpful Start Page by default when VS is started, is where all your code is displayed. This window can contain many documents, each indicated by a tab, so you can easily switch between several files by clicking their filenames. It also has other functions: It can display GUIs that you are designing for your projects, plain-text files, HTML, and various tools that are built into VS. You will come across all of these in the course of this book.

Above the main window are toolbars and the VS menu. Several different toolbars can be placed here, with functionality ranging from saving and loading files to building and running projects to debugging controls. Again, you are introduced to these as and when you need to use them.

Here are brief descriptions of each main feature that you will use the most:

  • The Toolbox toolbar pops up when the mouse moves over it. It provides access to, among other things, the user interface building blocks for Windows applications. Another tab, Server Explorer, can also appear here (it is selectable via the View Server Explorer menu option) and includes various additional capabilities, such as providing access to data sources, server settings, services, and more.

  • The Solution Explorer window displays information about the currently loaded solution. A solution is VS terminology for one or more projects along with their configurations. The Solution Explorer window displays various views of the projects in a solution, such as what files they contain and what is contained in those files.

  • Just below the Solution Explorer window you can display a Properties window, not shown in Figure 2–3 because it appears only when you are working on a project (you can also toggle its display using View Properties Window). This window allows a more detailed view of the project’s contents, enabling you to perform additional configuration of individual elements. For example, you can use this window to change the appearance of a button in a Windows form.

  • Also not shown in the screenshot is another extremely important window: the Error List window, which you can display using View Error List. It shows errors, warnings, and other project-related information. The window updates continuously, although some information appears only when a project is compiled.

This may seem like a lot to take in, but it doesn’t take long to get used to. You start by building the first of your example projects, which involves many of the VS elements just described.


VS is capable of displaying many other windows, both informational and functional. Many of these can share screen space with the windows mentioned here, and you can switch between them using tabs. Many of these windows are used later in the book, and you’ll probably discover more yourself when you explore the VS environment in more detail.

Visual C# 2008 Express Edition

With VCE you don’t have to worry about changing the settings. Obviously, this product isn’t going to be used for Visual Basic programming, so there is no equivalent setting to worry about here. When you start VCE for the first time, you are presented with a screen that is very similar to the one in VS (see Figure 2–4).

Beginning Microsoft Visual C# 2008

Figure 2–4

Console Applications

You use console applications regularly in this book, particularly at the beginning, so the following Try It Out provides a step-by-step guide to creating a simple one. This Try it Out includes instructions for both VS and VCE.

  1. Create a new console application project by selecting File New Project in VS or File New Project in VCE, as shown in Figure 2–5.

Beginning Microsoft Visual C# 2008

Figure 2–5

  1. In VS, select the Visual C# node in the Project Types pane of the window that appears, and the Console Application project type in the Templates pane (see Figure 2–6). In VCE, simply select Console Application in the Templates pane (see Figure 2–7). In VS, change the Location text box to C:\BegVCSharp\Chapter02 (this directory is created automatically if it doesn’t already exist). For both VS and VCE, leave the default text in the Name text box (ConsoleApplication1) and the other settings as they are (refer to Figure 2–6).

Beginning Microsoft Visual C# 2008

Figure 2–6

Beginning Microsoft Visual C# 2008

Figure 2–7

  1. Click the OK button.

  2. If you are using VCE, after the project is initialized click the Save All button on the toolbar or select Save All from the File menu, set the Location field to C:\BegVCSharp\Chapter02, and click OK.

  3. Once the project is initialized, add the following lines of code to the file displayed in the main window:

    namespace ConsoleApplication1
       class Program
          static void Main(string[] args)
             // Output text to the screen.
             Console.WriteLine(“The first app in Beginning C# Programming!”);
  4. Select the Debug Start Debugging menu item. After a few moments you should see the window shown in Figure 2–8.

Beginning Microsoft Visual C# 2008

Figure 2–8

  1. Press any key to exit the application (you may need to click on the console window to focus on it first).

The preceding display appears only if the Visual C# Developer Settings are applied, as described earlier in this chapter. For example, with Visual Basic Developer Settings applied, an empty console window is displayed, and the application output appears in a window labeled Immediate. In this case, the Console.ReadKey() code also fails, and you see an error. If you experience this problem, the best solution for working through the examples in this book is to apply the Visual C# Developer Settings—that way, the results you see match the results shown here. If this problem persists, then open the Tools → Options dialog and uncheck the Debugging → Redirect all output option, as shown in Figure 2–9.

Beginning Microsoft Visual C# 2008

Figure 2–9


For now, we won’t dissect the code used thus far because the focus here is how to use the development tools to get code up and running. Clearly, both VS and VCE do a lot of the work for you and make the process of compiling and executing code simple. In fact, there are multiple ways to perform even these basic steps—e.g., you can create a new project by using the menu item mentioned earlier, by pressing Ctrl+Shift+N, or by clicking the corresponding icon in the toolbar.

Similarly, your code can be compiled and executed in several ways. The process you used previously—selecting Debug → Start Debugging—also has a keyboard shortcut (F5) and a toolbar icon. You can also run code without being in debugging mode using the Debug → Start Without Debugging menu item (or by pressing Ctrl+F5), or compile your project without running it (with debugging on or off) using Build → Build Solution or F6. Note that you can execute a project without debugging or build a project using toolbar icons, although these icons don’t appear on the toolbar by default. Once you have compiled your code, you can also execute it simply by running the .exe file produced in Windows Explorer, or from the command prompt. To do this, open a command prompt window, change the directory to C:\BegVCSharp\Chapter02\ConsoleApplication1\ConsoleApplication1\bin\Debug\, type ConsoleApplication1, and press Enter.

In future examples, when you see the instructions “create a new console project” or “execute the code,” you can choose whichever method you want to perform these steps. Unless otherwise stated, all code should be run with debugging enabled. In addition, the terms “start,” “execute,” and “run” are used interchangeably in this book, and discussions following examples always assume that you have exited the application in the example.

Console applications terminate as soon as they finish execution, which can mean that you don’t get a chance to see the results if you run them directly through the IDE. To get around this in the preceding example, the code is told to wait for a key press before terminating, using the following line:


You will see this technique used many times in later examples. Now that you’ve created a project, you can take a more detailed look at some of the regions of the development environment.

The Solution Explorer

The first window to look at is the Solution Explorer window in the top right corner of the screen. It is the same for both VS and VCE (as are all the windows examined in this chapter unless otherwise specified). By default this window is set to auto-hide, but you can dock it to the side of the screen by clicking the pin icon when it is visible. The Solution Explorer window shares space with another useful window called Class View, which you can display using View Class View. Figure 2–10 shows both of these windows with all nodes expanded (you can toggle between them by clicking on the tabs at the bottom of the window when the window is docked).

Beginning Microsoft Visual C# 2008

Figure 2–10

This Solution Explorer view shows the files that make up the ConsoleApplication1 project. The file to which you added code, Program.cs, is shown along with another code file, AssemblyInfo.cs, and several references.

All C# code files have a .cs file extension.

You don’t have to worry about the AssemblyInfo.cs file for the moment. It contains extra information about your project that doesn’t concern us yet.

You can use this window to change what code is displayed in the main window by double-clicking .cs files; right-clicking them and selecting View Code; or selecting them and clicking the toolbar button that appears at the top of the window. You can also perform other operations on files here, such as renaming them or deleting them from your project. Other file types can also appear here, such as project resources (resources are files used by the project that might not be C# files, such as bitmap images and sound files). Again, you can manipulate them through the same interface.

The References entry contains a list of the .NET libraries you are using in your project. You’ll look at this later; the standard references are fine for now. The other view, Class View, presents an alternative view of your project by showing the structure of the code you created. You’ll come back to this later in the book; for now the Solution Explorer display is appropriate. As you click on files or other icons in these windows, you may notice that the contents of the Properties window (shown in Figure 2–11) changes.

The Properties Window

This window (select View Properties Window if it isn’t already displayed) shows additional information about whatever you select in the window above it. For example, the view shown in Figure 2–11 is displayed when the Program.cs file from the project is selected. This window also displays information about other selected items, such as user interface components (as shown in the “Windows Forms Applications” section of this chapter).

Beginning Microsoft Visual C# 2008

Figure 2–11

Often, changes you make to entries in the Properties window affect your code directly, adding lines of code or changing what you have in your files. With some projects, you spend as much time manipulating things through this window as making manual code changes.

The Error List Window

Currently, the Error List window (View → Error List) isn’t showing much of interest because there is nothing wrong with the application. However, this is a very useful window indeed. As a test, remove the semicolon from one of the lines of code you added in the previous section. After a moment, you should see a display like the one shown in Figure 2–12.

Beginning Microsoft Visual C# 2008

Figure 2–12

In addition, the project will no longer compile.


In Chapter 3, when you start looking at C# syntax, you will learn that semicolons are expected throughout your code—at the end of most lines, in fact.

This window helps you eradicate bugs in your code because it keeps track of what you have to do to compile projects. If you double-click the error shown here, the cursor jumps to the position of the error in your source code (the source file containing the error will be opened if it isn’t already open), so you can fix it quickly. You also see red wavy lines at the positions of errors in the code, so you can quickly scan the source code to see where problems lie.

Note that the error location is specified as a line number. By default, line numbers aren’t displayed in the VS text editor, but this is something well worth turning on. To do so, tick the Line numbers check box in the Options dialog (selected via the Tools → Options menu item). It appears in the Text Editor C# General category, as shown in Figure 2–13.

Beginning Microsoft Visual C# 2008

Figure 2–13


In VCE you must select Show All Settings for this option to become available, and the list of options looks slightly different from Figure 2–13.

Many useful options can be found through this dialog, and you will use several of them later in this book.

Windows Forms Applications

It is often easier to demonstrate code by running it as part of a Windows application than through a console window or via a command prompt. You can do this using user interface building blocks to piece together a user interface.

The following Try It Out shows just the basics of doing this, and you’ll see how to get a Windows application up and running, without a lot of details about what the application is actually doing. Later you take a detailed look at Windows applications.

  1. Create a new project of type Windows Forms Application (VS or VCE) in the same location as before (C:\BegVCSharp\Chapter02; and if you are using VCE, save the project to this location after you create it) with the default name WindowsFormsApplication1. If you are using VS and the first project is still open, make sure the Create New Solution option is selected to start a new solution. These settings are shown in Figures 2–14 and 2–15.

Beginning Microsoft Visual C# 2008

Figure 2–14

Beginning Microsoft Visual C# 2008

Figure 2–15

  1. Click OK to create the project. You should see an empty Windows form. Move the mouse pointer to the Toolbox bar on the left of the screen, then to the Button entry of the All Windows Forms tab, and double-click the entry to add a button to the main form of the application (Form1).

  2. Double-click the button that has been added to the form.

  3. The C# code in Form1.cs should now be displayed. Modify it as follows (only part of the code in the file is shown here for brevity):

          private void button1_Click(object sender, EventArgs e)
             MessageBox.Show(“The first Windows app in the book!”);
  4. Run the application.

  5. Click the button presented to open a message dialog box, as shown in Figure 2–16.

Beginning Microsoft Visual C# 2008

Figure 2–16

  1. Exit the application by clicking the x in the top right corner, as per standard Windows applications.


Again, it is plain that the IDE has done a lot of work for you and made it simple to create a functional Windows application with little effort. The application you created behaves just like other windows—you can move it around, resize it, minimize it, and so on. You don’t have to write the code to do that—it works. The same is true for the button you added. Simply by double-clicking it, the IDE knew that you wanted to write code to execute when a user clicked the button in the running application. All you had to do was provide that code, getting full button-clicking functionality for free.

Of course, Windows applications aren’t limited to plain forms with buttons. If you look at the toolbar where you found the Button option, you see a whole host of user interface building blocks, some of which may be familiar already. You will use most of these at some point in the book, and you’ll find that they are all easy to use, saving you a lot of time and effort.

The code for your application, in Form1.cs, doesn’t look much more complicated than the code in the previous section, and the same is true for the code in the other files in the Solution Explorer window. Much of the code generated is hidden by default. It is concerned with the layout of controls on the form, which is why you can view the code in Design View in the main window—it’s a visual translation of this layout code. A button is an example of a control that you can use, as are the rest of the UI building blocks found in the Windows Forms section of the Toolbox bar.

You can take a closer look at the button as a control example. Switch back to the Design View of the form using the tab on the main window, and click once on the button to select it. When you do so, the Properties window in the bottom right corner of the screen shows the properties of the button control (controls have properties much like the files shown in the last example). Ensure that the application isn’t currently running, scroll down to the Text property, which is currently set to button1, and change the value to ClickMe, as shown in Figure 2–17.

Beginning Microsoft Visual C# 2008

Figure 2–17

The text written on the button in Form1 should also reflect this change.

There are many properties for this button, ranging from simple formatting of the color and size to more obscure settings such as data binding settings, which enable you to establish links to databases. As briefly mentioned in the previous example, changing properties often results in direct changes to code, and this is no exception. However, if you switch back to the code view of Form1.cs, you won’t see any change in the code.

To see the modified code, you need to look at the hidden code mentioned previously. To view the file that contains this code, expand Form1.cs in the Solution Explorer, which reveals aForm1.Designer.cs node. Double-click on this file to see what’s inside.

At a cursory glance, you might not notice anything in this code reflecting the button property change at all. This is because the sections of C# code that deal with the layout and formatting of controls on a form are hidden (after all, you hardly need to look at the code if you have a graphical display of the results).

VS and VCE use a system of code outlining to achieve this subterfuge. You can see this in Figure 2–18.

Beginning Microsoft Visual C# 2008

Figure 2–18

Looking down the lefthand side of the code (just next to the line numbers if you’ve turned them on), you may notice some gray lines and boxes with + and—symbols in them. These boxes are used to expand and contract regions of code. Toward the bottom of the file is a box with a + in it and a box in the main body of the code reading Windows Form Designer generated code. This label is basically saying, “Here is some code generated by VS that you don’t need to know about.” You can look at it if you want, however, and see what you have done by changing the button properties. Simply click on the box with the + in it and the code will become visible, and somewhere in there you should see the following line:

         this.button1.Text = “Click Me”;

Without worrying too much about the syntax used here, you can see that the text you typed in the Properties window has popped up directly in your code.

This outlining method can be very handy when you are writing code because you can expand and contract many other regions, not just those that are normally hidden. Just as looking at a book’s table of contents can help you by providing a quick summary of the contents, looking at a series of collapsed regions of code can make it much easier to navigate through what can be vast amounts of C# code.


In this chapter you were introduced to some of the tools that you will use throughout the rest of this book. You have had a quick tour around the Visual Studio 2008 and Visual C# 2008 Express Edition development environments and used them to build two types of applications. The simpler of these, the console application, is quite enough for most of your needs and enables you to focus on the basics of C# programming. Windows applications are more complicated but are visually more impressive and intuitive to use for anyone accustomed to a Windows environment (and let’s face it, that’s most of us).

Now that you know how to create simple applications, you can get down to the real task of learning C#. After dealing with basic C# syntax and program structure, you move on to more advanced object-oriented methods. Once you’ve covered all that, you can begin to learn how to use C# to gain access to the power available in the .NET Framework.

In this chapter, you learned:

  • How the Visual Studio 2008 and Visual C# 2008 Express Edition development environments work.

  • How to create a simple console application.

  • How to get a Windows application up and running.

For subsequent chapters, unless otherwise specified, instructions refer to VCE, although, as shown in this chapter, adapting these instructions for VS is not difficult, and you can use whichever IDE you prefer, or to which you have access.

Beginning Microsoft® Visual C#® 2008, Copyright © 2008 by Wiley Publishing, Inc., ISBN: 978-0-470-19135-4, Published by Wiley Publishing, Inc., All Rights Reserved. Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates.