Programming .NET with C#

CSharp Programming Tutorial: No column can substitute for a good primer on the language, but in this series I hope to focus in on some of the more interesting aspects and challenges facing the novice C# programmer. Along the way I will talk about object-oriented analysis and design, good programming practice, and the ins and outs of producing, debugging, and shipping high quality software.

by Jesse Liberty,

This is the first of a series of monthly columns on Programming for the Microsoft .NET platform. For the first few months, I'll concentrate on Microsoft's new object oriented programming language: C# (C-Sharp).

No column can substitute for a good primer on the language, but in this series I hope to focus in on some of the more interesting aspects and challenges facing the novice C# programmer. Along the way I will talk about object-oriented analysis and design, good programming practice, and the ins and outs of producing, debugging, and shipping high quality software.

C# in context
Programmers will come to Microsoft C# from various backgrounds. Some will come from C++ or Java, confident in their understanding of object oriented programming and at home in the C-family syntax. For these programmers, the transition to the C# syntax will be very easy.

Many Visual Basic 6 programmers are realizing that the move to Visual Basic .NET is a giant leap. (In fact, it is so great a transition that some VB6 programmers have started calling the new language VB.NOT!) Many of these programmers tell me that they are going to switch to C# because they are convinced that the transition from VB6 to C# will be no more difficult than the transition from VB6 to VB.NET, and they believe that C# programmers will earn more in the market. No one is certain if these earnings predictions are correct, but there is no mistaking the fact that many VB6 programmers are in fact learning C#.

Finally, some programmers will come to C# with little or no related experience, and they will have to learn all of it at once: C#, object oriented programming, Windows* and Web development, and the .NET platform itself.

Whatever your background, the common theme of all C# programming is this: the language exists to facilitate .NET development. Thus, any discussion of C# must always return to the issue of building .NET applications. This will be the focus of this and future columns.

Opportunity knocks
Every ten years or so the world shifts under our feet, and we either adjust or we get left behind. In the 1980s I was programming in Unix using *. We were doing great things, building on-line services hosted on Intel® 286 processor computers. Unix offered a multitasking environment not then available under DOS.

In the early 1990s I switched from C to C++ and from Unix to Windows. Suddenly I was writing event-driven programs for Graphical User Interfaces (GUIs), and C++ was a much better fit. In C++ you could create new user types to represent the various controls and widgets drawn on the console (such as buttons, list boxes, windows, and so forth).

I wrote a lot of books on C++ and I think it is a great language, but I can read the handwriting on the wall. The next platform is .NET and the language of choice for .NET development is C#.

The .NET platform is virtually a new operating system. Rather than creating an object oriented operating system and all the tools for it, all at once, Microsoft has released the .NET platform to sit on top of its existing Windows operating systems. I would not be at all surprised to see the .NET platform merged into the next release of Windows; in fact, I'd be surprised if that didn't happen. The advantages of .NET development are so clear and convincing that it is not surprising that Microsoft has put all its chips on .NET.

The .NET platform
.NET is built on a Common Language Runtime that acts as the interface between your programs and the underlying operating system. The CLR provides just-in-time compiling of your C# programs (explained later in this article), as well as the bedrock support for exception handling, type checking, and so forth.

The .NET Framework Base Class Library (BCL) is built on top of the CLR and offers a rich set of classes to provide the plumbing for Windows and Web development. The BCL includes classes for I/O, security, threading, collections, and so forth.

On top of the BCL, .NET offers ADO.NET-an object oriented model for database development. I'll devote a future column to ADO.NET; this is the next generation model for interacting with databases.

You build your applications atop this infrastructure. Typically, you'll create one of three types of programs: a Web application, a Web Service, or a Windows desktop application.

Web applications
In the 1990s, Microsoft offered what has become one of the most popular platforms for Web development: Active Server Pages (ASP). The successor to ASP is ASP.NET. I'll explore ASP.NET in detail in a future column, but the short story is this: ASP.NET improves on ASP in every way; separating HTML from the compiled code that supports it. Most important, from our perspective, the code behind ASP.NET pages can be any .NET language, including C#.

Web services
Web Services are, essentially, Web applications with no user interface. A Web Service offers a service to another program, over the Web. This allows for distributed processing using standard Web protocols.

The canonical Web Service is one that takes a stock symbol and returns a quote. You can imagine Web Services that offer stock quotes, message forwarding, or other support services. Microsoft's new My Services (formerly Hailstorm) product builds Web Services as commercial offerings.

Windows applications
You can also, of course, build traditional desktop applications in C#, using Windows Forms. Windows Forms are very similar to Web Forms. It is my personal prediction that one day (soon?) Microsoft will combine Web Forms and Window Forms, but for now they are two similar but distinct technologies.

The Common Language Specification
What Microsoft really did was to create a new unnamed language for .NET, which is detailed in the Common Language Specification (CLS)—the specification for all .NET languages. This allows Microsoft (and other vendors) to provide a plethora of syntaxes for their single common language. Thus, C# and VB.NET are really the same language with different faces!

All CLS languages must support the Common Type System (CTS), ensuring that types used or created in VB.NET are compatible with types used or created in C#. In fact, the CLS is so well defined that you can create a class (user defined type) in C# and derive from it (specialize it) in VB.NET! You can throw an exception in a VB.NET method and catch it in a C# method! (I'll define all these terms and talk about how to create classes and manage exceptions in future columns.)

Neither C# nor Visual Basic .NET produces executable programs. Instead, all CLS languages produce Microsoft Intermediate Language (MSIL-often shortened to IL) code. The Just In Time compiler built into the CLR compiles the IL code when your program is run (and caches it in memory so that it need only be compiled once). C# programs and VB.NET programs produce virtually identical IL code; again, they really are just about the same language with different syntax.

Visual Basic .NET versus C#
Okay, I won't duck the question: if C# and Visual Basic .NET produce the same code, why would you choose one over the other? While there are minor differences in the capabilities of the languages, there is no good technical reason to prefer one to the other, in a vacuum. That is, from a purely technical viewpoint, these languages are virtually interchangeable.

But you are not programming in a vacuum and there are a few good non-technical reasons to choose one over the other.

First and foremost, you might decide to go to C# or VB.NET based on your existing comfort with one or another syntax. Arguably, if you are a Java or C++ programmer, the transition to C# will be easier for you. Similarly, if you are a VB programmer, the transition to VB.NET will be smoother.

The second consideration is purely mercenary. Historically, C++ programmers have earned more than VB6 programmers. Setting aside whether or not this was justified, it was the market reality for most programmers. Many managers tell me they expect more skill (analysis, design, and so forth) from their C++ programmers. Thus, when hiring for .NET, these same managers expect to pay C# programmers more than they will pay VB.NET programmers. This may change over time, but it may not; if it turns out that VB.NET programmers were VB6 programmers, and C# programmers were generally C++/Java programmers, the disparity may continue.

Given that the transition to VB.NET is difficult (as noted previously), many VB6 programmers will opt to transition to C# now, in the hope that C# will offer higher compensation. In addition, there are currently many more VB than C++ programmers, and so there is some expectation that C# programmers may be in relatively scarce supply for a while; again driving up their earnings potential.

Caveat: I have a vested interest in millions of VB programmers switching to C# and so my perspective may not be objective.

What is C# like?
The best way to get a handle on C# is to write a program. Let's write three: a console application, a Windows application, and a Web application. Because this is a column and not a primer, I'll skip over lots of details and focus on the key issues. In this case, the key issue is this: programming in C# is a blast!

Let's get started. I'll assume you have installed .NET Beta 2 or the release candidate, and that you've installed Visual Studio .NET and IIS. If not, please do so now. I'll wait. . . .

Good. Fire up Visual Studio .NET and click New Project. In the Project Types window, click Visual C# projects. In the Templates window, click Console Application. Set the location to a reasonable directory (you may want to click Browse to set this), and in the name field type HelloWorldConsole, as shown in Figure 1.


creating the console application

Figure 1. Creating the Console Application

Click OK. The new console application opens for you. Visual Studio .NET tries to be helpful. It creates a new file named Class1.cs and in that file it puts the following code:



using System;
namespace HelloWorldConsole

   /// <summary>
   /// Summary description for Class1.
   /// </summary>
   class Class1
   
      static void Main(string[] args)
      
         //
         // TODO: Add code to start application here
         //
      
   

There is a lot going on here. I'll cover all of it very briefly. The first line:


   using System

tells the compiler that you'll be using the System namespace. Namespaces are just a way to divide the world of identifiers (method names, and so forth) so that my Class1 doesn't conflict with a Class1 I might purchase from a vendor.

The program begins by creating a new namespace for my program:


namespace HelloWorldConsole

This is optional but convenient. It isolates the names of all the classes and methods I create within the HelloWorldConsole namespace.

The three slash comments:


   /// <summary>
   /// Summary description for Class1.
   /// </summary>

are XML documentation-a topic I'll try to cover in a later column. For now, you can ignore them or delete them; it won't matter either way.

The heart of this program is the creation of the class Class1. You are, of course, free to change the name of the class (and the file that holds it), but for now let's leave it as it is.

Within the class definition is the method Main. Main is the entry point for the console application: that is, execution starts here. Let's skip over the characteristics of Main (that it is static, returns void, takes a parameter named args) and just accept for now that this is how Main is created. We'll come back to these particulars in the future.

Within Main is a comment:


         //
         // TODO: Add code to start application here
         //

C# supports three types of comments:

  1. XML documentation comments (///).
  2. C++ style comments (//). Anything from the // comment mark to the end of the line is ignored by the compiler.
  3. C style comments (/* */). Anything between the opening comment mark /* and the closing comment mark */ is ignored by the compiler.
Comments are, essentially, programmer notes; added to the code to remind you of what you were trying to accomplish. I could write an entire column on using comments well; for now I'll restrict myself to this: comment often, and don't say what you are doing, say why.

Remove the comments here, and replace them with this line:


   Console.WriteLine("Hello Intel!");

C# is filled with classes and objects. Again, this is a big topic, but in short, a class defines a new type, and an object is an instance of that type. Thus, int is a type, 5 is an instance of the type int. Dog is a class, my dog Milo is an object: instance of Dog.

Console is a class that represents your output console (typically your monitor). Console has a method WriteLine. Here you are invoking that method and passing in the string Hello Intel!. The net effect is that this line will be written to your monitor.

(Object oriented programmers please note, in C# static methods are called on the class and instance methods are called on objects. In this case, WriteLine is a static method of Console and thus is called on the class. Non-object oriented programmers, don't fret, all will be made clear in time.)

Compile and run your program by pressing F5. The output should look like Figure 2.


output from the console application

Creating the Windows application
To see what creating a Windows application is like, close the current solution and click New Project again. This time click Windows Application in the Templates window, and set the name to HelloWorldWindows.

Visual Studio .NET puts you into the development environment. Depending on how you are set up, you may see the Toolbox on the left, the Form Designer in the middle, the Solution Explorer on the right with the Properties window below it and a series of tabbed windows below the designer, as shown in Figure 3. If you don't see the windows you expect, click View or Debug to open the various windows. If the Toolbox does not stay open, click its tab and then use the push pin to pin it in place.

the form designer and associated windows

Figure 3. The Form Designer and Associated Windows
(click for larger image)

There is much to explore here, but we just want to get a quick feel for what is involved. Drag a Label onto the form, and then use the Properties window to set its Name to lblOutput and its Text to "Hello Intel!". Click the Font property to set the font size to 14, and click the label itself to show its resizing handles. Resize to fit.

Drag a button onto the form below the label. Set its Name property to btnChange and its text property to Change!. Click its Font property to set the font to bold and feel free to set other properties to change the background color or otherwise make the button more attractive.

Add another button next to it named btnExit with the text Exit. Shift-click the two buttons to select them both, and then use the menu choice Format/MakeSameSize/Both to make the buttons the same size.

Click the label and shift-click the Change button to highlight them both. Choose Format/Align/Lefts to align the label with the left side of the left button. Now resize the label (click it and drag the handle) to as wide as both the buttons combined.

Shrink the form to fit by clicking the form and resizing. Your form should look similar to Figure 4.


the resized form

Figure 4. The Resized Form

It is time to wire the event handlers to the buttons. When a button is clicked, an event is raised. Event handling is a rather complex subject, but you can ignore all the details for now and let Visual Studio .NET do the work for you. Double-click the Exit button. VS.NET will create an event handler; you just supply the code.

You should find yourself with the cursor inside the btnExit_Click method. Add the following line of code:



   Application.Exit();

That's it for that handler. Click the Design tab to return to the form, and then double-click the Change button. Again you are in the event handler. Add this line:


lblOutput.Text = "GoodBye Intel!";

When you type the period after lblOutput, VS.NET will pop up a list of all the properties and methods of the label object. You can choose Text. and then continue typing.

Be careful-C# is case sensitive. You must type lblOutput exactly; if you type LblOutput or lbloutput, C# will not recognize your label.

Run the application. Click the Change button. You should see the new message displayed, as shown in Figure 5.


testing the Windows application

Figure 5. Testing the Windows Application

That's it! You have a working Windows application. Click the Exit button to exit the application.

There is much more to say about Windows programming, of course, but you see how easy it is to bang together a simple application. Before I end for this month, let's do the same thing with a Web form.

Creating the Web form application
Close the Windows solution and create a new project, this time choosing ASP.NET Web Application from the Templates window. Name the application HelloWorldWeb. Visual Studio .NET creates a Web site for you. The Web pages are in the directory you choose on the opening dialog, and the solution files are stored in a directory under the default project location.

The Designer that opens in VS.NET is similar to the one for Windows development, as shown in Figure 6.

the Web development environment

Figure 6. The Web Development Environment
(click for larger image)

Once again drag a label onto the form and use the Properties window to set its name to lblOutput and its text property to "Hello Intel!". Click the + sign next to the Font property to expand the font attributes, and set the size to larger. Stretch the label to hold the Goodbye Intel! phrase. Notice that you can place the label exactly where you want it; the default view of the form uses absolute positioning.

Add just one button this time. Set the Name to btnChange and the Text to Change!. Again, you can use the font to set the text to bold.

Click the HTML tag to look at the HTML this page is using. There is a lot going on here. I'll save a detailed explanation for a future column, but the important fact is that the designer is just using HTML. You can write this entire HTML page without the designer, just as you could write the entire Windows page without Visual Studio .NET, but it is far easier to use Visual Studio .NET.

Go back to the Design view and double-click the button. VS.NET displays the code behind page. This is a separate file that will be compiled, providing code support for server side processing for your controls. In this case you are in the event handler for the button's click. Add the same code you used in the previous example:


lblOutput.Text = "Goodbye Intel!";

Press Ctrl-F5 to compile and run the program. Your page should open in a browser. Click Change. The page is posted back to the server and a new page is sent with the new text as shown in Figure 7.


the Web application

Figure 7. The Web Application

Before you close this application, click View/Source. Examine the source code sent. The important thing to note is that what is sent to the client is just HTML. Nowhere do you see the code supporting the page; that is held on the server. ASP.NET pages are just HTML and thus can be viewed with any browser.

Conclusion
We've just scratched the surface with C#, and in future columns I hope to dive into more detail.

I'm very much looking forward to writing this column and to receiving your feedback, inquiries, and concerns. To give me feedback or to ask questions, please go to my Web site: http://www.LibertyAssociates.com and click Books and then Articles and Other Publications. You'll find a link to information about this column. Also, be sure to check out my support discussion group on http://forums.delphiforums.com/LibertyBooks, where you'll find a folder for questions and issues about this column.

Thanks.

About the author
Jesse Liberty is the international best selling author of Programming C# and Programming ASP.NET (O'Reilly), as well as Teach Yourself C++ In 21 Days (SAMS), Clouds To Code (Wrox), and a dozen books on object-oriented Web and applications development. Jesse is the president of Liberty Associates, Inc., (http://www.LibertyAssociates.com) where he provides on-site training in .NET development, as well as custom programming and consulting.

Get a pdf version of this article: click download, below.


Subscribers who liked this article also read:
Case Study: Animation Company Improves Rendering and Cost with Intel Xeon Processor
Maya Entertainment Ltd. is a leading computer animation and visual eff...
Strong wireless LAN security: a reality today
from Intel Corp. Companies have long recognized that wireless tec...

If you're interested in this topic, these articles may be helpful:

Rich Client Platform tutorial, part 2
by Ed Burnette, SAS. Eclipse.org The Rich Client Platform (RCP) all...
ASP.NET tutorial: binding a datareader to a datalist using SQL server and VisualBasic.NET
from EAServe.com First, import the System.Data.SqlClient namespace ...
Migrating Java to C# manually: four case studies
by Jason A. Fletcher, application engineer, Intel Software and Solu...
Non-stop .NET
by Alan Zeichick, principal analyst, Camden Associates Web services...
Overview of enterprise-class application servers
by Matt Gillespie, technical author. Intel Corp. The application ...

Related Jobs:

Technical Trainer #57926 - CA - San Rafael - Autodesk, Inc.
General Summary: As the technical training specialist for the Infr...
Technical Writer #149616 - WA - Redmond - Microsoft Corporation
Is your dream to write for cutting-edge video games in a world-class g...
Programming Writer #135494 - WA - Redmond - Microsoft Corporation
The Windows Client SDK team is looking for an experienced Programming ...
Software Developer #WBSD - MA - Burlington - Webex, Inc.
Software Developer Location: Burlington Job Code: WBSD ...
Programming Writer #145005 - WA - Redmond - Microsoft Corporation
Do you enjoy the idea of all the challenge and growth that a startup o...
Research Analyst #R-152-05 - VA - Arlington - McDonald Bradley, Inc.
R-152-05 Research Analyst Apr 14, 2005 Arlington,Virginia Send...
Senior Technical Writer #0770 - WA - Seattle - F5 Networks, Inc
Work alone or as the lead of a writing team. Research, plan, write,...
Security Architect #54561 - CA - Sacramento - EML Incorporated
Duration: 6 months The Security Architect will be responsible for c...
Coordinator of Instructional Technology/Campus Web Development #25-05/06 - CA - Vallejo - California State University
Campus: Maritime Academy Appointment Type: Probationary Categ...
Documentation Manager-Software Products #58123 - CA - San Rafael - Autodesk, Inc.
Directeur de la documentation : Produits logiciels Rsum des fonc...