Export (0) Print
Expand All

An Introduction to Programming Using Microsoft Visual C# 2005 Express Edition

Visual Studio 2005
 

Andrew W. Troelsen, Microsoft MVP
Intertech Training

August 2004

Summary: This article introduces programming with the C# language using the Microsoft Visual C# 2005 Express Edition Integrated Development Environment (IDE). Using various example projects, readers will be exposed to several aspects of the C# programming language and key concepts of the .NET platform. (23 printed pages)

Download the Code.msi sample file.

Note   This article assumes you're a hobbyist, student, or programming-minded individual interested in exploring the C# programming language and the .NET platform using Visual C# 2005 Express Edition. No prior exposure to C# is assumed or expected, however, some previous programming experience will be helpful.

Applies to:
   
Microsoft Visual C# 2005 Express Edition

Contents

What Is Visual C# 2005 Express Edition?
High Level Features of Visual C# 2005 Express
Visual C# 2005 Express Projects
Assemblies, Namespaces, and Types
Theory into Practice: Using External Types
Handing Exceptions with C# Express
Handing the Exception Programmatically
Creating a C# Class Library Project
Building a Windows Forms Application
Go Forth and Code: Visual C# 2005 Express Starter Kits
Summary

What Is Visual C# 2005 Express Edition?

A .NET application can be created using a variety of approaches. Die-hard developers are free to take the commando approach and build .NET programs using a no-frills text editor (such as notepad.exe) and the C# command line compiler (csc.exe). While the .NET Software Development Kit (SDK) is freely downloadable from Microsoft (www.microsoft.com/net), this approach will surely result in hand cramps, due to the lack of code generation utilities (wizards), graphical debuggers, and IntelliSense functionality in the SDK .

To help lessen the burden of building software at the command line, many .NET developers make use of visual tools such as Microsoft's full-featured IDE, Visual Studio .NET 2003 (http://msdn.microsoft.com/vstudio). While this product is very powerful, the Enterprise Edition may be cost prohibitive for the .NET hobbyist and/or college student . To be honest, unless you are a professional software engineer, the magnitude of options provided by Visual Studio .NET 2003 typically complicates, rather than facilitates, the learning process.

Somewhere between notepad.exe and Visual Studio .NET 2003 sits Microsoft's newest IDE, Visual C# 2005 Express Edition. At the time of this writing, the beta version of Visual C# 2005 Express Edition is offered free of charge through a Web download (http://msdn.microsoft.com/express). Given the relatively small size, Visual C# 2005 Express can be easily acquired even using a 56K modem connection.

Visual C# 2005 Express is actually one of several members in the Express family. Specifically, Microsoft provides the following Express Edition products:

  • Visual Web Developer 2005 Express: A lightweight tool for building dynamic Web sites and XML Web services using ASP.NET.
  • Visual Basic 2005 Express: A streamlined programming tool ideal for beginning programmers to learn how to build Windows applications.
  • Visual C# 2005 Express, Visual C++ 2005 Express, and Visual J# 2005 Express: Targeted programming tools for students and enthusiasts who wish to learn the fundamentals of computer science.
  • SQL Server 2005 Express: An entry-level database management system geared towards hobbyists, enthusiasts, and students developers.

In a nutshell, the Express Edition product lineup is an ideal entry point for hobbyist, students, and newcomers to the .NET platform. If this sounds like you, download and install Visual C# 2005 Express and read on.

High Level Features of Visual C# 2005 Express

Visual C# 2005 Express offers many of the key features you would expect to find in a .NET development environment, for example:

  • An ANSI compliant C# 2.0 compiler
  • A full-featured integrated debugger
  • Advanced IntelliSense capabilities
  • Design time support for Windows Forms development
  • Support for local database access
  • Extremely simple access to XML Web services

It is also important to understand what Visual C# 2005 Express does not bring to the table. Specifically, Visual C# 2005 Express doesn't directly support:

  • ASP.NET Web applications
  • Construction of XML Web services
  • Mobile application development (cell phones, PDAs, Windows CE devices)
  • Remote database connection tools

Within the pages that follow, you will be provided with an introduction of C# and the .NET platform using Visual C# 2005 Express. Please be aware however that this article is not intended to be a comprehensive tutorial on the C# programming language, the .NET platform, or the Visual C# 2005 Express IDE. The conclusion of this article provides additional links to .NET Web sites to further your learning process.

Visual C# 2005 Express Projects

A Visual C# 2005 Express project is composed of any number of C# source code files (which take a *.cs file extension), supporting content files (XML documents, application icons, images, and so forth) and referenced assemblies (defined later in this article). Rather than forcing us to create the same boilerplate code for a specific type of project (Windows Forms application, Console application, and so forth), Visual C# 2005 Express provides a number of core project types, described in the following table.

Visual C# 2005 Express Project TypeDefinition
Windows ApplicationCreates a new Windows Forms project.

This type of project is used to create desktop application such as Microsoft Word.

Class LibraryThis project is used to create a reusable code library (packaged as *.dll files), which can be used across your .NET applications.
Console ApplicationThis project creates a Console based application.

These applications are very useful when learning a new programming language such as C#, as you do not need to concern yourself with the construction of graphical user interfaces (GUIs).

Empty ProjectThis option generates a project with no initial C# code files. This can be helpful when you wish to import existing files into a new project using the Project | Add Existing Item menu item.

To begin investigating C#, we will create a brand new Console application named MyCSharpExpressApp. The File | New | Project menu selection activates the new project dialog as shown in Figure 1.

ms379606.usingcsharpexpress-fig1(en-US,VS.80).gif

Figure 1. Creating a new Console Application project

At this point, you may wish to save using the File | Save All menu selection. From the resulting dialog box, specify a location of your choosing, as shown in Figure 2.

ms379606.usingcsharpexpress-fig2(en-US,VS.80).gif

Figure 2. Saving the current project

Note   This first Console application will not provide much functionality, but will serve as a vehicle to examine some fundamental concepts. We will build a complete (and more interesting) application later in this article.

Assemblies, Namespaces, and Types

Before we get too far along in this first example, it is important to come to grips with some key terms of the .NET programming trade. In my years of teaching software professionals, I can say with complete certainty that the distinction between an assembly, namespace, and type consistently confuses new .NET developers. Let's try to prevent this from happening to you.

When you build a project you are actually creating a .NET assembly. Formally speaking, an assembly is a physical file (which typically take a *.exe or *.dll file extension) that you can directly view on your hard drive using the Windows Explorer.

The Visual C# 2005 Express Solution Explorer window displays a subfolder named References, which lists the set of assemblies used by the current project. While different projects tend to reference a unique set of assemblies, Figure 3 shows the assemblies for the current Console Application.

ms379606.usingcsharpexpress-fig3(en-US,VS.80).gif

Figure 3. Referenced assemblies for a Console Application project

As you are building more elaborate .NET applications, you will often need to use assemblies beyond the set included by a particular project. To do so, C# Express provides the Add Reference dialog box, which can be activated using the Project | Add Reference dialog box. You have no need to add additional assemblies at this point. Figure 4 shows the dialog box in question.

ms379606.usingcsharpexpress-fig4(en-US,VS.80).gif

Figure 4. The C# Express Add Reference Dialog box

An assembly contains a set of namespaces. Simply put, a namespace is nothing more than a collection of types that are semantically related. Understand that it is very common for a single assembly to contain multiple namespaces. For example, the mscorlib.dll assembly contains namespaces for file input and output (System.IO), collection types (System.Collections), general purpose utility types (System), and so on.

Note   Every .NET application automatically references mscorlib.dll, therefore you will never need to manually reference this core library.

A namespace in turn defines any number of types. As of .NET 2.0, there are five kinds of types that are briefly (the key word being briefly) described in the following table.

.NET TypeMeaning in Life
ClassA class is a blueprint for an object. Like the blueprints to a house, a class can be used to create objects. Just like houses, the properties of each individual object can be totally different (blue vs red houses), but the blueprint will never change.
InterfaceInterfaces define a set of common methods a class or interface may support. Interfaces allow you to define a set of members a class or structure must support.
StructureSimply put, structures are lightweight class types. This type of type is ideal when modeling mathematical, geometric, or other fairly atomic data. Structures lack the object-oriented features of classes, such as inheritance.
EnumerationEnumerations (or simply enums) are a named collection of name/value pairs. Enums allow you to define known values for use in your program.
DelegateDelegates boil down to type safe function pointers. These types are the foundation of the .NET event architecture. Regardless of if you are handling a Button's Click event or handing a post back to an ASP.NET Web page, delegates are the underlying plumbing.

When a C# project needs to make use of types within a given assembly, the first step is to reference the *.dll using the Add Reference dialog as shown in Figure 4. The second step is to add a using directive at the top of the file to specify the namespace you wish to access. In reality, the C# using directive is nothing more a shorthand for specifying lengthy namespaces in your code, allowing us to use just File in our code in place of the full name System.IO.File. To illustrate, assume the following code:

using System;

namespace SomeProgram
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an ArrayList and Hashtable 
      // (the hard way).
      System.Collections.ArrayList a =
        new System.Collections.ArrayList();
      System.Collections.Hashtable h =
        new System.Collections.Hashtable();
    }
  }
}

Here, we are creating an ArrayList and Hashtable type, both of which are within the System.Collections namespace. Rather than prefixing the namespace to the type directly, you can save yourself some typing with the following using directive:

using System;
using System.Collections;  // Add this!

namespace SomeProgram
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an ArrayList and Hashtable 
      // (the easy way).
      ArrayList a = new ArrayList();
      Hashtable h = new Hashtable();
    }
  }
}

As you may suspect, your major goal as a .NET programmer is to become acquainted with the assemblies, namespaces, and types that you have at your disposal. Thankfully, C# Express provides an integrated object browser utility that can be activated from the View | Other Windows | Object Browser menu item. Using this tool, you can view the namespaces and types within each referenced assembly, as shown in Figure 5.

ms379606.usingcsharpexpress-fig5(en-US,VS.80).gif

Figure 5. The C# Express Object Browser

Theory into Practice: Using External Types

Now let's add some code to the MyCSharpExpressApp project. When you are building an application that needs to interact with the local file system, you need to use the System.IO namespace. By way of an example, update your file's using directives and enter the following code within your Main() method:

#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;  // Need this for IO types!
#endregion

namespace MyCSharpExpressApp
{
  class Program
  {
    static void Main(string[] args)
    {
      // Open a file named myInfo.txt
      // located on the root C:\ drive.          
      string myFileContents;
      myFileContents = File.ReadAll(@"C:\myInfo.txt");

      // Now print it to the console.                
      Console.WriteLine(myFileContents);
      Console.ReadLine();    
    }
  }
}

This application makes use of the File.ReadAll() method to open the specified file and return the contents as a string. In this case, the contents of a file named myInfo.txt is displayed directly to the console. Assume this file has been created with notepad.exe and that it contains a single line of text, as shown in Figure 6.

ms379606.usingcsharpexpress-fig6(en-US,VS.80).gif

Figure 6. The myInfo.txt file

Save this file directly in your C drive and run the application using the Debug | Start Without Debugging menu option. If all is well, you should see the output as shown in Figure 7.

ms379606.usingcsharpexpress-fig7(en-US,VS.80).gif

Figure 7. Your first C# Express application

Note   If this example does not work as expected, keep reading. The next section examines how to debug runtime exceptions using Visual C# 2005 Express.

Now assume you wish to display this information within a Windows Forms message box, rather than the console. To do so you will need to:

  • Reference the System.Windows.Forms.dll assembly.
  • Specify that you are 'using' the System.Windows.Forms namespace.
  • Pass the string returned from File.ReadAll() to the MessageBox.Show() method.

First, reference System.Windows.Forms.dll using the Add References dialog box shwon in Figure 8.

ms379606.usingcsharpexpress-fig8(en-US,VS.80).gif

Figure 8. Referencing the System.Windows.Forms.dll assembly

Next, update your code as so:

#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;  // Need this for IO types!
using System.Windows.Forms;  // Need this for MessageBox!
#endregion

namespace MyCSharpExpressApp
{
  class Program
  {
    static void Main(string[] args)
    {
      // Open a file named myInfo.txt
      // located on the root C:\ drive.          
      string myFileContents;
      myFileContents = File.ReadAll(@"C:\myInfo.txt");

      // This time, place in a message box.      
      MessageBox.Show(myFileContents);
      Console.ReadLine();    
    }
  }
}

Once you run your application again, you will find the contents of your file displayed within a Windows Forms message box like Figure 9.

ms379606.usingcsharpexpress-fig9(en-US,VS.80).gif

Figure 9. Interacting with the MessageBox class type

Handing Exceptions with C# Express

The current example has made the rather large assumption that a file named myInfo.txt does indeed exist on the root C drive. If this is not the case, you will receive a runtime error (more formally termed, a runtime exception). Visual C# 2005 Express can help you diagnose such errors. To illustrate, delete (or rename) the myInfo.txt file and debug your program using the Debug | Start menu selection. As you can see from Figure 10, you are provided with numerous details regarding the current exception, as well as suggestions for correcting the issue.

ms379606.usingcsharpexpress-fig10(en-US,VS.80).gif

Figure 10. Debugging exceptions using Visual C# 2005 Express

To fix the current problem, rename your text file to myInfo.txt.

Handing the Exception Programmatically

Given that the presence of an external file is not discovered until your application is running, C# programmers make use of a technique termed structured exception handling. As you will see, structured exception handing involves the use of a small number of C# keywords (most importantly try and catch).

When you are calling methods (such as the File.ReadAll() method) that may return a runtime exception, wrap the statements within a try scope. If an exception is triggered, the error is passed to a related catch scope, where you can handle the problem gracefully. If each statement in the try scope executes without error, the catch block is skipped completely. To test this out firsthand, update your current code as so:

namespace MyCSharpExpressApp
{
  class Program
  {
    static void Main(string[] args)
    {
      // Attempt to open a file named myInfo.txt
      // located on the root C:\ drive.          
      string myFileContents;
      try
      {
        myFileContents = File.ReadAll(@"C:\myInfo.txt");
        MessageBox.Show(myFileContents);
      }
      catch(FileNotFoundException ex)
      {                
        Console.WriteLine("Error: {0}",
          ex.Message);
      }      
      Console.ReadLine();
    }
  }
}

Here, we are making use of the Message property of the FileNotFoundException class to format our error message in the case that the file is missing, as shown in Figure 11.

ms379606.usingcsharpexpress-fig11(en-US,VS.80).gif

Figure 11. Programmatically handling the FileNotFoundException

So much for this initial example application. Now that you have a better understand of the basics, let's create a more complex (and interesting) C# application.

Creating a C# Class Library Project

Our next goal is to build a .NET class library named ManagerSpeakLib.dll. Begin by closing the current MyCSharpExpressApp project (using File | Close Project) and create a new Class Library project named ManagerSpeakLib, as shown in Figure 12. Notice that you are given the option of 'discarding' the MyCSharpExpressApp project if you haven't saved it previously, allowing you to create quick test projects without cluttering your system with unnecessary code.

ms379606.usingcsharpexpress-fig12(en-US,VS.80).gif

Figure 12. Creating a new Class Library project

The role of this class (which we'll rename to ManagerSpeak) is to return a randomly generated phrase that mocks the chatter often found in the corporate world. Update the ManagerSpeak class with a method named StateTheProblem():

#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion

namespace ManagerSpeakLib
{
  public class ManagerSpeak
  {
    public ManagerSpeak(){}

    // This method returns a randomly selected problem.
    public string StateTheProblem()
    {
      string[] possibleProblem = {
        "I think we really need to leverage...",
        "We can emerge as a dominant force if we optimize...",
        "To achieve an effective use of synergy we need to consider..."};
      Random r = new Random();
      return possibleProblem[r.Next(3)];
    }
  }
}

Here we are making use of the System.Random class to return one of the three statements in the local string array. The Next() method is used to obtain a random number, which in this case is between 0 and 2 (for a total of three possiblilties: 0, 1, 2).

Of course, every problem needs a solution. Therefore, add another method to the ManagerSpeak class named GetSolution():

public class ManagerSpeak
{
...
  // This method returns a randomly selected solution.
  public string GetSolution()
  {
    // String arrays with 10 segments each.
    string[] list1 = { "integrated",
      "individualized", "cooperative", "flexible", "authentic",
      "functional", "responsive", "alternative", "performance",
      "cognitive"};

    string[] list2 = { "behavioral",
      "relevant", "criteria", "prescriptive", "perceptual",
      "facilitated", "modular", "diagnostic", "structured",
      "situational"}; 

    string[] list3 = { "strategies",       
      "methodologies", "assessments",   "analysis",   "learning",      
      "interaction", "objectives", "concepts", "recoveries",
      "management"};
  
    // Make use of a System.Random type to 
    // obtain a random string from each array.
    Random r = new Random();
    int a = r.Next(10);
    int b = r.Next(10);
    int c = r.Next(10);

    // Now create and return the statement.
    string newMsg = list1[a] + " " + list2[b] + " " + list3[c];
    return newMsg;
  }
}

At this point, save your entire project (in a folder of your choice) using the File | Save All menu command. Compile your new code library by activating the Build menu. At this point, you should find your new code library located under the Bin\Release subdirectory shown in Figure 13.

ms379606.usingcsharpexpress-fig13(en-US,VS.80).gif

Figure 13. The ManagerSpeakLib.dll class library

As you may know, *.dll assemblies cannot be directly executed by double-clicking on them from the Windows Explorer. Rather, they are loaded by the runtime when another application requests them. Given this, our next step is to build an application that uses ManagerSpeakLib.dll.

Building a Windows Forms Application

The application to make use of ManagerSpeakLib.dll will be a new Windows Forms project named ManagerSpeakClient (Figure 14).

ms379606.usingcsharpexpress-fig14(en-US,VS.80).gif

Figure 14. Building a Windows Forms application

Once the project has loaded, you will notice that a visual Form designer is opened automatically, as shown in Figure 15.

ms379606.usingcsharpexpress-fig15(en-US,VS.80).gif

Figure 15. The Visual C# 2005 Express Form designer

Visual C# 2005 Express supplies numerous tools that make the process of building graphical user interfaces (GUIs) a snap (all of which are accessible from the View menu). For example the Toolbox dialogue shown in Figure 16 displays numerous Windows Forms components that can be used to build your form's user interface.

ms379606.usingcsharpexpress-fig16(en-US,VS.80).gif

Figure 16. The Windows Forms Toolbox

On a related note, the Properties window shown in Figure 17 allows you to configure the currently selected widget (Form, Button, and so on) at design time.

ms379606.usingcsharpexpress-fig17(en-US,VS.80).gif

Figure 17. The Properties window

Using these tools, create a simple user interface that consists of a Button and Label as shown in Figure 18. Note that I set the Text property (using the Properties window) of the Label, Form, and Button to fitting descriptions.

ms379606.usingcsharpexpress-fig18(en-US,VS.80).gif

Figure 18. The Manager Client Form

Next we need to reference ManagerSpeakLib.dll using the Add References dialog (again, activated using the Project | Add Reference menu item). Be aware that when you wish to reference your own custom *.dlls, you will need to select the Browse tab and manually navigate to the location of the code library you wish to use, as shown in Figure 19.

ms379606.usingcsharpexpress-fig19(en-US,VS.80).gif

Figure 19. Referencing your ManagerSpeakLib.dll assembly

To complete our Windows Forms application, double click on the Button using the Form designer. This will automatically handle the Click event for the button type and generate the following code:

private void button1_Click(object sender, EventArgs e)
{
        
}

At this point you are free to add the code to manipulate the ManagerSpeak class. Here is the complete code update (notice the C# using directive for ManagerSpeakLib).

#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using ManagerSpeakLib; // Need this!
#endregion

namespace ManagerSpeakClient
{
  partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      // Make a manager.
      ManagerSpeak m = new ManagerSpeak();

      // Get the problem.
      string currentProblem = m.StateTheProblem();

      // Get the solution.
      string solution = m.GetSolution();

      // Show the details!
      MessageBox.Show(string.Format("{0}\n{1}", 
                      currentProblem , solution)); 
    }
  }
}

Now run your Windows Forms application and click the Button. You will find a randomly generated problem/solution, shown in Figure 20, in the very distinct (and generally annoying) dialect of 'manger-speak'.

ms379606.usingcsharpexpress-fig20(en-US,VS.80).gif

Figure 20. Behold, manager-speak!

This wraps up our Windows Forms application. Fell free to save this project on your machine using the File | Save All menu option.

Go Forth and Code: Visual C# 2005 Express Starter Kits

At this point you have created three different C# Express projects (a Console program, a Class Library, and a Windows Forms Application). While this introductory article did not cover all aspects of the C# language (or the full functionality of Visual C# 2005 Express), I do hope you are in a good position for further exploration.

To wrap up this article, I leave you with the topic of starter kits. Simply put, a starter kit is a complete C# application that intends to illustrate numerous programming concepts. Moreover, starter kits provide full documentation, code walkthroughs, and suggestions for extending the out-of-the-box functionality. One default starter kit is the Screen Saver Starter Kit, which can be selected from the New Project dialog box shown in Figure 21. You can launch the kit using the File | New | Project... menu selection.

ms379606.usingcsharpexpress-fig21(en-US,VS.80).gif

Figure 21. Selecting the Screen Saver starter kit

Once you have selected the Screen Saver project and clicked the OK button, the starter kit's documentation file (ScreenSaverStarterKit.htm), shown in Figure 22, is loaded by the IDE. Here you can learn about the basic composition of the project at hand.

ms379606.usingcsharpexpress-fig22(en-US,VS.80).gif

Figure 22. Reading up on the Screen Saver starter kit

As you can see, this starter kit provides details of each code file, as well as a step-by-step walkthrough of the project's design. You can run the application by pressing the F5 key. If you are connected to the Internet, you will be able to view RSS (Really Simple Syndication) feeds presented on top of a rotating set of background images.

Summary

Visual C# 2005 Express is an ideal entry point for newcomers to the .NET platform. As you have seen in this article, the IDE provides a set of project types, a graphical debugger, and numerous Windows Forms designers. While this article did not offer a complete tour of the IDE, you are hopefully more comfortable navigating around your active projects.

The bulk of this article was spent introducing some core terms in the .NET universe. Recall that assemblies are binary files that contain any number of namespaces. A namespace in turn defines any number of types (classes, interfaces, structures, enumerations, and delegates). Using these types, .NET programmers are able to build any sort of application.

Hopefully, this article has stirred up some interest in checking out C# and the .NET platform in further detail. If you require additional information regarding C#, you may wish to consult the following links:

Andrew Troelsen is a consultant and trainer with Intertech Training. Andrew is the author of numerous books including the award winning C# and the .NET Platform Second Edition (Apress 2002). He also authored a monthly column for (of all places) MacTech where he explored .NET development on Unix-based systems using the SSCLI, Portable.NET and Mono CLI distributions.

Show:
© 2014 Microsoft