Chapter 2: Writing a C# Program

Applies to: Visual Studio 2010

Provided by: Karli Watson

Referenced Image

Buy This Book from Publisher

This topic contains the following sections.

  • What You Will Learn in This Chapter
  • The Development Environments
  • Console Applications
  • Windows Forms Applications
  • Summary
  • What You Learned in this Chapter
  • Copyright

What You Will Learn in This Chapter

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

  • How to write a simple console application

  • How to write a Windows Forms application

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 2010 (VS) and Visual C# 2010 Express (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 begin 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 prefer, 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.

After 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.

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 2010

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.

Figure 2-1

Referenced Image

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.

Figure 2-2

Referenced Image

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.

Figure 2-3

Referenced Image

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 you need to use them.

Here are brief descriptions of each of the main features 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 (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, as you learned in the previous chapter, 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 provides 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.

Note

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. Several 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# 2010 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).

Figure 2-4

Referenced Image

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. It includes instructions for both VS and VCE.

Try It Out: Creating a Simple Console Application

  1. Create a new console application project by selecting File ⇨ New ⇨ Project in VS or File ⇨ New Project in VCE, as shown in Figures 2-5 and 2-6.

  2. In VS, ensure that the Visual C# node is selected in the Installed Templates pane of the window that appears, and choose the Console Application project type in the middle pane (see Figure 2-7). In VCE, simply select Console Application in the Templates pane (see Figure 2-8). 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 Figures 2-7 and 2-8).

  3. Click the OK button.

  4. 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 Save.

  5. 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!″);
             Console.ReadKey();
          }
       }
    }
    
  6. Select the Debug ⇨ Start Debugging menu item. After a few moments you should see the window shown in Figure 2-9.

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

    Figure 2-5

    Referenced Image

    Figure 2-6

    Referenced Image

    Figure 2-7

    Referenced Image

    Figure 2-8

    Referenced Image

    Figure 2-9

    Referenced Image

    In VS, 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-10.

Tip

For now, we won't dissect the code used thus far because the focus here is on 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—for instance, 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.

Figure 2-10

Referenced Image

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. After 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.

Note

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:

   Console.ReadKey();

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 Solution Explorer window is 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-11 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).

Note

In VCE, the Class View window is only available if you turn on Expert Settings, which you can do through the Tools | Settings | Expert Settings menu item.

Figure 2-11

Referenced Image

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.

Note

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 by 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-12) changes.

Figure 2-12

Referenced Image

The Properties Window

The Properties 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-12 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).

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-13.

Figure 2-13

Referenced Image

In addition, the project will no longer compile.

Note

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. Red wavy lines appear at the positions of errors in the code, so you can quickly scan the source code to see where problems lie.

The error location is specified as a line number. By default, line numbers aren't displayed in the VS text editor, but that 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-14.

Note

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-14.

Figure 2-14

Referenced Image

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.

Try It Out: Creating a Simple Windows Application

  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-15 and 2-16.

    Figure 2-15

    Referenced Image

    Figure 2-16

    Referenced Image

  2. 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).

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

  4. 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!″);
          }
    
  5. Run the application.

  6. Click the button presented to open a message dialog box, as shown in Figure 2-17.

  7. Click OK, and then exit the application by clicking the X in the top-right corner, as per standard Windows applications.

    Figure 2-17

    Referenced Image

Tip

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. Look at the toolbar where you found the Button option and you'll see a whole host of user interface building blocks, some of which may be familiar. 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 Click Me, as shown in Figure 2-18.

Figure 2-18

Referenced Image

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 a Form1.Designer.cs node. Double-click that 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. That's 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-19.

Figure 2-19

Referenced Image

Looking down the left 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 the box with the + in it and the code will become visible, and somewhere within it 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 what it contains, 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.

Summary

This chapter introduced some of the tools that you will use throughout the rest of this book. You have had a quick tour around the Visual Studio 2010 and Visual C# 2010 Express development environments and used them to build two types of applications. The simpler of these, the console application, is quite enough for most needs, and it 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.

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.

What You Learned in this Chapter

Topic

Key Concepts

Visual Studio 2010 settings

This book requires the C# development settings option, chosen when first run or by resetting settings.

Console applications

Console applications are simple command-line applications, used in much of this book to illustrate techniques. Create a new console application with the Console Application template that you see when you create a new project in VS or VCE. To run a project in debug mode, use the Debug ⇨ Start Debugging menu item, or press F5.

IDE windows

The project contents are shown in the Solution Explorer window. The properties of the selected item are shown in the Properties window. Errors are shown in the Error List window.

Windows Forms applications

Windows Forms applications are applications that have the look and feel of standard desktop applications, including the familiar icons to maximize, minimize, and close an application. They are created with the Windows Forms template in the New Project dialog box.

Beginning Visual C# 2010, Copyright © 2010 by Wiley Publishing, Inc., ISBN: 978-0-470-50226-6, 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.