Introduction
AAHC

Click on A to make all fonts on the page smaller.

Click on A to make all fonts on the page larger.

Click on HC to toggle high contrast mode. When you move your mouse over some bold words in high contrast mode, related words are automatically highlighted. Text is shown in black and white.


Welcome to the O'Reilly School of Technology C#.NET 2: C# Programming in the .NET Framework course!

Course Objectives

When you complete this course, you will be able to:

In this course you will gain a deeper understanding of object oriented programming. You will learn about data types and scope, and create programs using models, classes, objects, methods, and constructors, as well as the ways in which these elements relate to one another. File Input/Output (I/O) topics are also covered, allowing you to both read from and write to files. As you create increasingly complex projects, you will learn ways to debug your code as well.

You will create several applications throughout the course, which will enhance your professional portfolio and also contribute toward certificate completion.

NoteThis lesson duplicates the first two lessons of the first C# course. If you've taken that course, you may either skip this lesson, or browse through it to refresh your knowledge of the material. However, you'll still complete the homework to demonstrate that you know the material—and to get your certificate for this course!

Learning with O'Reilly School of Technology Courses

As with every O'Reilly School of Technology course, we'll take a user-active approach to learning. This means that you (the user) will be active! You'll learn by doing, building live programs, testing them and experimenting with them—hands-on!

To learn a new skill or technology, you have to experiment. The more you experiment, the more you learn. Our system is designed to maximize experimentation and help you learn to learn a new skill.

We'll program as much as possible to be sure that the principles sink in and stay with you.

Each time we discuss a new concept, you'll put it into code and see what YOU can do with it. On occasion we'll even give you code that doesn't work, so you can see common mistakes and how to recover from them. Making mistakes is actually another good way to learn.

Above all, we want to help you to learn to learn. We give you the tools to take control of your own learning experience.

When you complete an OST course, you know the subject matter, and you know how to expand your knowledge, so you can handle changes like software and operating system updates.

Here are some tips for using O'Reilly School of Technology courses effectively:

Lesson Format

We'll try out lots of examples in each lesson. We'll have you write code, look at code, and edit existing code. The code will be presented in boxes that will indicate what needs to be done to the code inside.

Whenever you see white boxes like the one below, you'll type the contents into the editor window to try the example yourself. The CODE TO TYPE bar on top of the white box contains directions for you to follow:

CODE TO TYPE:
White boxes like this contain code for you to try out (type into a file to run).

If you have already written some of the code, new code for you to add looks like this. 
    
If we want you to remove existing code, the code to remove will look like this.
  
We may also include instructive comments that you don't need to type.  

We may run programs and do some other activities in a terminal session in the operating system or other command-line environment. These will be shown like this:

INTERACTIVE SESSION:
The plain black text that we present in these INTERACTIVE boxes is 
provided by the system (not for you to type). The commands we want you to type look like this.

Code and information presented in a gray OBSERVE box is for you to inspect and absorb. This information is often color-coded, and followed by text explaining the code in detail:

OBSERVE:
Gray "Observe" boxes like this contain information (usually code specifics) for you to observe.

The paragraph(s) that follow may provide addition details on information that was highlighted in the Observe box.

We'll also set especially pertinent information apart in "Note" boxes:

NoteNotes provide information that is useful, but not absolutely necessary for performing the tasks at hand.

TipTips provide information that might help make the tools easier for you to use, such as shortcut keys.

WARNINGWarnings provide information that can help prevent program crashes and data loss.

Understanding the Learning Sandbox Environment

We'll be doing lots of work in Visual Studio, Microsoft's Integrated Development Environment (IDE) for working with C#. In the next lesson, we will cover in-depth how to use Visual Studio. For this first lesson, we'll introduce you to the visual cues to help you learn and experiment, and then we'll help you create your first C# application!

When you see this icon, you should save your work. You can save whenever you like, and we strongly encourage you to get in the habit of saving your projects frequently. Whenever you pause to think, let your mouse pointer find on the Toolbar! It's a great habit to get into!

The OST Plug-In

We've added a menu item to the Visual Studio system for your convenience. Use the OST menu to get to your syllabus for this course at any time. Your menu may have different courses, or only this course, listed.

TipThis may serve as a "panic button," too; if your Visual Studio menus start to get confusing in the course of your work, you can always get back to the default view by selecting this course from the OST menu.

Let's Do Something!

Okay, enough talk; let's create our first C# program! Traditionally, a first program is one that simply displays the text "Hello, World!" so we'll walk you through the steps. The goal is to make Studio do something NOW! We'll learn more about the Studio development environment in the next lesson. We'll move quickly through making this first program; here's an overview of the steps:

  1. Create a new C# Windows Form Application project called HelloWorld.
  2. Open and "pin" the Toolbox.
  3. Drag a Label control from the Toolbox onto the Windows Form.
  4. Open the Properties Window.
  5. Set the display Text for the Label control to "Hello, World!"
  6. Save the HelloWorld project.
  7. Run the HelloWorld project.

Let's get started!

NoteAfter you create the project below, you won't be able to see this lesson text. To get it back, right-click on the tab marked Form.cs[Design] and select New Horizontal Tab Group. This will split the screen with the lesson page at the top and the form designer at the bottom. You will need to do this each time you create a new project. If more than one project is open, you can just drag its tab to the lower tab group to move it.

Creating a New Horizontal Tab Group

When you finish, you should see something like this.

Now, remembering those steps, let's create our project. Select the File menu, then New, then Project (in the future, we'll show this kind of menu sequence like this: File | New | Project):

In the New Project dialog, in the left column, check that Visual C# | Windows is selected. In the middle column, make sure Windows Forms Application is selected (these options should already be selected by default). At the bottom of the dialog, in the Name textbox, replace WindowsFormsApplication1 with HelloWorld or Hello World (you can include spaces in project names to make them more readable, if you like). Click OK when you finish typing the name.

At this point, you'll need to perform the steps described earlier to get the lesson text back.

Now, we want to have our tools available all the time, so click Toolbox:

When the Toolbox expands, click on the Auto Hide "pin" icon at the top of the Toolbox window so that the pin is pointing down rather than horizontal. The Toolbox will now stay displayed.

Find the Label control under the Common Controls option.

Click and drag the Label onto the grey area under the box named Form1 in the middle of Visual Studio.

Right-click on the "label1" text on Form1, and choose Properties.

In the Properties Window at the bottom right of Studio, find the Text property in the left column. In the column to the right of Text, change "label1" to Hello, World!.

Click Save in the Studio Toolbar (at top) to save the project.

Find the green Start Debugging button in the Studio Toolbar. Click it to run the program!

Click the small black "x" or Close icon to close your first Windows C# application.

Congratulations!!! You've just created and run your first C# application!!!

Closing and Reopening a Solution

Eventually, of course, you will love programming so much you'll never want to stop! Still, you might need to take a break from time to time, so you need to know how to close a solution and to reopen it when you return.

With your Hello World solution selected in the Solution Explorer, select File | Close Solution. The Solution Explorer will now be empty.

To reopen the solution, select File | Open | Project/Solution...

In the dialog that appears, double-click your HelloWorld (or Hello World) project folder, and then select your Hello World solution.

Double-click Form1.cs to bring back the form designer (and the tools in the Toolbox).

Studio IDE

Software development in .NET uses the Microsoft Visual Studio Integrated Development Environment (IDE). During this course, we will refer to Visual Studio as the Studio IDE, Studio, or IDE.

An IDE supplies most if not all of the tools you will need to develop software. This lesson will familiarize you with the features of the Studio IDE, and show how to use those features and components to begin creating your own software.

A Quick Tour

The Studio IDE initial Start Page looks like this (a popup dialog from the System Tray may alert you to an optional Customer Experience Improvement Program feature. You may participate or not by clicking on the popup dialog):

The Start Page is a convenient presentation of many initial tasks you may want to perform when first opening Studio.

Close this page by clicking on the small x on the tab labeled Start Page.

TipTo view the Start Page again at any time, select View | Start Page.

The Studio IDE includes a File menu along the top of the application, buttons just below the menu, and components below the buttons. All Studio IDE elements are context sensitive, which means that certain elements may be disabled or unavailable depending on what you are doing. You will notice that many of the buttons look dim, or gray. These buttons are disabled:

Move your mouse pointer over one of the icons and pause until a popup appears; here, for example, is the Save All icon popup:

These popups display the icon's function (and keyboard shortcut, if available). The icon function corresponds to the same functionality available through the menu. For example, the Save All functionality is also available from the File menu.

The Studio IDE contains many more elements than initially appear, and as you work more with Studio, you will learn to add the elements that you prefer.

Right-click in the blank area at the top of Studio next to the menu items or buttons, and select Web Browser. Icons appropriate to a web browser will now be visible:

NoteThe Studio IDE contains an embedded web browser for viewing online or offline content.

To see the Microsoft Developer Network Forums home page, click the MSDN Forums icon:

You will see content similar to this:

This is a valuable resource for learning more about developing software using Visual Studio—we'll visit it again later.

Close the Forums tab by clicking the in the Visual Studio Category tab header.

TipIf you lose this lesson window, or otherwise get confused by the rearranging of windows that Visual Studio may do, select OST | Reset Windows from the top menu.

At the top left corner of the Studio window, just below the icons, you will see the Toolbox panel, which we "pinned" in the last lesson.

If it's not already open, click the word Toolbox to expand the button into a window:

You'll also see an expanded area to the right of the Studio window labeled Solution Explorer.

Both the Toolbox and Solution Explorer panels contain the same three controls at the top right: They are labeled Window Position (the arrowhead image), Auto Hide (the pushpin image), and Close (the X). Window Position controls the location and appearance of the panel. Auto Hide, if selected (the pushpin being horizontal) controls the display of the panel as your mouse moves over its icon. Close will close and hide the panel.

Click the Toolbox Window Position and select Float:

Now you can move the floating Toolbox panel around the screen by clicking and dragging it.

TipIf you double-click on the top of the panel (the title bar), the panel will maximize. To restore it to its original size, double-click the title bar again.

Click the Toolbox Window Position button again and select Dock as Tabbed Document. Note that the three panel controls are gone. To restore the Toolbox to floating, you need to select the Window | Float menu option.

To restore the Toolbox as a docked element on the left of the screen, select the Toolbox Window Position button again, and select Dock.

TipIf you close or hide the Toolbox button or window, you can unhide it by selecting View | Toolbox.

Toggle the Auto Hide pushpin and note the behavior when the pushpin is vertical versus when it is horizontal. When you finish, make sure it is vertical so the Toolbox remains onscreen.

Creating Your Second Project

Creating software is an interactive process, and experimenting is strongly encouraged! Feel free to experiment more with the Studio IDE.

Now that you have an idea of how the buttons work, and how to navigate around a few of the Studio elements, let's create another C# project. As we learned in the first lesson, software developers often create a simple program that displays the words "Hello World." Let's create this traditional first program again, but with a twist.

Select File | New | Project. The New Project dialog presents a rather daunting list of possible project types; just select Windows Forms Application. Then, change the default project name to GraphicalHelloWorld:

NoteRemember to right-click the Form1.cs tab and select New Horizontal Tab Group so you can see this lesson text again!

You now see the Studio environment including the GraphicalHelloWorld project. Note the Form1 form. This form represents the visual element of the program we will create. A Windows Form Application uses the concept of a rectangular form for presenting information to the user. You will also notice that the Solution Explorer now contains information.

The Form1 component is a Visual Designer known as the Windows Forms Designer. Studio contains many Visual Designers that we will use throughout these lessons.

The Solution Explorer lists information in a hierarchical display related to solutions and projects. A project represents a single item, such as the GraphicalHelloWorld application, but a solution contains one or more projects. Every project belongs to a solution by default. You will use the Solution Explorer to add or access items within a project or solution, as well as to configure build settings, publish projects and solutions, and perform other activities.

Applications typically contain lines of programming code that run, or execute. When you run an application on your computer, you are running a published version of that application. As an application developer, you can run both a published version, and a development, or debug, version.

Locate the green play button labeled Start Debugging. You may also press F5, or select Debug | Start Debugging from the menu. The same form that you saw in Studio appears as a separate window:

Although this form looks like an independent application, Studio is still connected to it. You can see how Studio is still linked to the running GraphicalHelloWorld application by the choices under the Debug menu.

To stop running an application, you can either close it using the icon at the top-right corner of the application, or you can switch back to Studio and click the blue Stop icon . All of the Debug commands are also available from the top Debug menu.

Click Close in the top-right corner of the running GraphicalHelloWorld application.

By default, a Windows Form Application is pretty empty. In our first C# project, we added the Hello World text using the Toolbox. The Toolbox contains components we can use in our application. Now we'll add the text again, and then change it to a graphical version of the text. Again, we will first use a label control.

Double-click the Label control in the Common Controls option in the list of hierarchical groupings of the Toolbox. A new label control appears on the form.

A label control may be used to display simple text for a variety of reasons. A text control is typically not a control that a user can click on.

Right-click on the label control in the form, and select Properties. Note the appearance of the Properties window in the bottom right of Studio (it may already have been visible, as in the image above). Scroll down the left column to the Text property, click on the field next to the Text property, and type Hello World to replace the "label1" text. To change the text of the label control in the form, you can either press Enter or click away from the field.

We will learn more about the different windows components of the Toolbox later.

Notice in the Solution Explorer that the name of the Form1 file is Form1.cs. You need to change the name of Form to something meaningful, in this case, GraphicalHellowWorld.cs. Click on Form1.cs to select it in the Solution Explorer. Once it is selected, the Properties window will show the Form1 properties. Change the File Name property from Form1.cs to GraphicalHelloWorld.cs and press Enter. You may see this dialog box:

This indicates that changing the filename will impact other portions of your code, and that Studio can automatically update all references to the old name to the new one. This feature of having the IDE assist you when you make such changes is known as refactoring, and we will see more refactoring opportunities later. For now, click Yes to perform the updates.

Press F5 to run the GraphicalHelloWorld application and view the Hello World text (if it doesn't run, click in the Design panel area where the form is, and try again). To stop running the application, click its Close button .

Tip Get in the habit of saving your work. Often, we will pause while we think about doing something. Train yourself to click Save or Save All during these idle times.

Click Save or Save All, or press Ctrl+S.

Programming Code

Before we can put a bit of a twist on the GraphicalHelloWorld application, we need to discuss the program code that makes it work. Studio includes a number of text or code editors to make writing your code a very interactive and efficient process.

Right-click the GraphicalHelloWorld.cs entry in the Solution Explorer and select View Code (again, you'll want to display it in a New Horizontal Tab Group):

Studio adds a new tab to the central window showing the programming code, also known as source code, for the form. This window, shown below, is a C# Code Editor. We will learn more about the code later.

TipTo increase the size of the source code window, you can hide the Toolbox window by "unpinning" the AutoHide pushpin.

Modify the form code to look exactly like the code shown below (remember: type the highlighted code yourself rather than cutting and pasting!). Note the addition of the line of code below InitializeComponent().

CODE TO TYPE: GraphicalHelloWorld
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
    
namespace GraphicalHelloWorld
{
    public partial class GraphicalHelloWorld : Form
    {
        public GraphicalHelloWorld()
        {
            InitializeComponent();
            // Hide the label to prevent obscuring graphical Hello World
            this.label1.Visible = false;
        }
    
        protected override void OnPaint(PaintEventArgs e)
        {
            // Call the OnPaint method of the base class
            base.OnPaint(e);
            // Call methods of the System.Drawing.Graphics object
            e.Graphics.DrawString("Graphical Hello World",
                new System.Drawing.Font("Arial", 16.0F, FontStyle.Italic),
                new SolidBrush(ForeColor), 10.0F, 10.0F);
        }
    }
}

NoteThe "using" section won't change much; you can collapse (and thus hide) the section by clicking the minus (-) icon to the left of it; to expand and view it again, click the plus (+).

Save your changes, and press F5 to run the modified program. Now the "Graphical Hello World" text in italics is drawn on the form, rather than using the label control:

So how does this code work? Let's OBSERVE and discuss it.

OBSERVE: GraphicalHelloWorld Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
    
namespace GraphicalHelloWorld
{
public partial class GraphicalHelloWorld : Form
    {
    public GraphicalHelloWorld()
        {
            InitializeComponent();
            // Hide the label to prevent obscuring graphical Hello World
            this.label1.Visible = false;
        }
    
        protected override void OnPaint(PaintEventArgs e)
        {
            // Call the OnPaint method of the base class
            base.OnPaint(e);
            // Call methods of the System.Drawing.Graphics object
            e.Graphics.DrawString("Graphical Hello World",
                new System.Drawing.Font("Arial", 16.0F, FontStyle.Italic),
                new SolidBrush(ForeColor), 10.0F, 10.0F);
        }
    }
}

NoteIn the OBSERVE box, we added color to different elements that we want to focus on. As you proceed with the lessons, you'll see this color-coding to identify different elements in the code, and to help clarify what is happening.

In the code above, this.label1.Visible = false; prevents the display of the Label control to prevent obscuring the drawing of "Hello World" text. Throughout the code, you see lines starting with "//." These are single-line comments, used to help document the code (and ignored at runtime). As you learn to program, you should add comments that help you and that document the functionality of your code.

Add // before the this.label1.Visible = false; line and save and rerun the program, then remove the // and save and run it again, to see what that line of code does.

The second change to the code adds an OnPaint method that draws the actual "Graphical Hello World" text on the Form. We will learn more about how this code works later.

NoteWhen you make changes to the code, Studio highlights these changes with a yellow bar at the left of the Code Editor window. Once you have saved your changes, the yellow bar changes to green. These "changed" bars will remain until the file is closed.

The Source Code Window

The source code created by Studio, and the code you later typed in, follow very strict rules, or language semantics. As you learn more about programming in C#, you will learn these rules. The source code window includes a number of helpful features, such as collapsible source code outlines shown by the gray lines with the minus signs at the left of the window. You can click on the minus signs to collapse one or more sections of code to ease the adding and editing of other code.

Click on the minus sign next to the line with the OnPaint text. Click on the plus sign that appears to redisplay the OnPaint source code.

The source code editor also includes an Intellisense feature that assists you with the language semantics, prompting for available elements when coding, and providing a autocompletion feature that, for example, adds a closing parenthesis ) when you enter an opening one (. We will focus more on this and other features of the source code editor later.

Before you move on to the next lesson, do your homework! Right-click in the window where this lesson text appears and select Back. Then, select Quiz for this lesson in the syllabus and answer the quiz questions. When you finish the quiz questions, click Hand it in at the bottom of that window. Then do the same with the Project(s) for the lesson. Your instructor will grade your quiz(zes) and project(s) and provide guidance if needed.

Now you're ready to move on where you'll dive right in, learning more about Visual Studio, and create another C# application!