- C# is Microsoft's object-oriented programming language designed for improving productivity in the development of Web applications
- Fully revised for C# 2005, this book begins with creating a C# program, then moves into C# and object-oriented programming fundamentals, Windows programming with C# and Visual Studio, and debugging and error handling
- A friendly, conversational approach to understanding C# is certain to get readers quickly creating applications
- The CD-ROM contains all the sample code in the book as well as bonus materials
About the Author
Stephen R. Davis, who goes by the name of Randy, lives with his wife and son near Dallas, Texas. He and his family have written numerous books, including C++ For Dummies and C++ Weekend Crash Course. Stephen works for L-3 Communications.
Chuck Sphar escaped Microsoft’s C++ documentation camps in 1997, after six years’ hard labor as a senior technical writer. He’s perpetrated two previous tomes, one on object-oriented programming for the Mac and one on Microsoft’s MFC class library. He’s currently finishing a novel about ancient Rome (againstrome.com) and gobbling mouthfuls of .NET programming. Chuck can be reached for praise and minor nits at email@example.com.
Read an Excerpt
C# 2005 For Dummies
By Stephen Randy Davis
John Wiley & SonsISBN: 0-7645-9704-3
Chapter OneCreating Your First C# Windows Program
In This Chapter
* What's a program? What is C#? Where am I?
* Creating a Windows program
* Making sure your Visual Studio 2005 C# is in tune
In this chapter, I explain a little bit about computers, computer languages, C#, and Visual Studio 2005. Then, I take you through the steps for creating a very simple Windows program written in C#.
Getting a Handle on Computer Languages, C#, and .NET
A computer is an amazingly fast, but incredibly stupid servant. Computers will do anything you ask them to (within reason), and they do it extremely fast - and they're getting faster all the time. As of this writing, the common PC processing chip can handle well over a billion instructions per second. That's billion, with a "b."
Unfortunately, computers don't understand anything that resembles a human language. Oh, you may come back at me and say something like, "Hey, my telephone lets me dial my friend by just speaking his name. I know that a tiny computer runs my telephone. So that computer speaks English." But it's a computer program that understands English, not the computer itself.
The language that computers understand is often called machine language. It is possible, but extremely difficult and error prone, for humans to write machine language.
For historical reasons, machine language is also known as assembly language. In the old days, each manufacturer provided a program called an assembler that would convert special words into individual machine instructions. Thus, you might write something really cryptic like MOV AX, CX. (That's an actual Intel processor instruction, by the way.) The assembler would convert that instruction into a pattern of bits corresponding to a single machine instruction.
Humans and computers have decided to meet somewhere in the middle. Programmers create their programs in a language that is not nearly as free as human speech but a lot more flexible and easy to use than machine language. The languages that occupy this middle ground - C#, for example - are called high-level computer languages. (High is a relative term here.)
What's a program?
What is a program? In one sense, a Windows program is an executable file that you can run by double-clicking its icon. For example, the version of Microsoft Word that I'm using to write this book is a program. You call that an executable program, or executable for short. The names of executable program files generally end with the extension .exe.
But a program is something else, as well. An executable program consists of one or more source files. A C# program file is a text file that contains a sequence of C# commands, which fit together according to the laws of C# grammar. This file is known as a source file, probably because it's a source of frustration and anxiety.
The C# programming language is one of those intermediate languages that programmers use to create executable programs. C# fills the gap between the powerful-but-complicated C++ and the easy-to-use-but-limited Visual Basic - well, versions 6.0 and earlier, anyway. (Visual Basic's newer .NET incarnation is almost on par with C# in most respects. As the flagship language of .NET, C# tends to introduce most new features first.) A C# program file carries the extension .CS.
Some wags have pointed out that C-sharp and D-flat are the same note, but you should not refer to this new language as D-flat within earshot of Redmond, Washington.
Finally, C# is an integral part of .NET.
.NET began a few years ago as Microsoft's strategy to open up the Web to mere mortals like you and me. Today it's bigger than that, encompassing everything Microsoft does. In particular, it's the new way to program for Windows. It also gives a C-based language, C#, the simple, visual tools that made Visual Basic so popular. A little background will help you see the roots of C# and .NET.
Internet programming was traditionally very difficult in older languages like C and C++. Sun Microsystems responded to that problem by creating the Java programming language. To create Java, Sun took the grammar of C++, made it a lot more user friendly, and centered it around distributed development.
When programmers say "distributed," they're describing geographically dispersed computers running programs that talk to each other - in many cases, via the Internet.
When Microsoft licensed Java some years ago, it ran into legal difficulties with Sun over changes it wanted to make to the language. As a result, Microsoft more or less gave up on Java and started looking for ways to compete with it.
Being forced out of Java was just as well because Java has a serious problem: Although Java is a capable language, you pretty much have to write your entire program in Java to get its full benefit. Microsoft had too many developers and too many millions of lines of existing source code, so Microsoft had to come up with some way to support multiple languages. Enter .NET.
.NET is a framework, in many ways similar to Java's libraries, because the C# language is highly similar to the Java language. Just as Java is both the language itself and its extensive code library, C# is really much more than just the keywords and syntax of the C# language. It's those things empowered by a thoroughly object-oriented library containing thousands of code elements that simplify doing about any kind of programming you can imagine, from Web-based databases to cryptography to the humble Windows dialog box.
The previous generation platform was made up of a hodgepodge of tools with cryptic names. .NET updates all that with Visual Studio 2005, with more focused .NET versions of its Web and database technologies, newer versions of Windows, and .NET-enabled servers. .NET supports emerging communication standards such as XML and SOAP rather than Microsoft's proprietary formats. Finally, .NET supports the hottest buzzwords since object-oriented: Web Services.
Microsoft would claim that .NET is much superior to Sun's suite of Web tools based on Java, but that's not the point. Unlike Java, .NET does not require you to rewrite existing programs. A Visual Basic programmer can add just a few lines to make an existing program "Web knowledgeable" (meaning that it knows how to get data off the Internet). .NET supports all the common Microsoft languages and more than 40 other languages written by third-party vendors (see gotdotnet.com/team/lang for the latest list). However, C# is the flagship language of the .NET fleet. C# is always the first language to access every new feature of .NET.
What is Visual Studio 2005? What about Visual C#?
You sure ask lots of questions. The first "Visual" language from Microsoft was Visual Basic, code-named "Thunder." The first popular C-based programming language from Microsoft was Visual C++. Like Visual Basic, it was called "Visual" because it had a built-in graphical user interface (GUI - pronounced gooey). This GUI included everything you needed to develop nifty-giffy C++ programs.
Eventually, Microsoft rolled all its languages into a single environment - Visual Studio. As Visual Studio 6.0 started getting a little long in the tooth, developers anxiously awaited Version 7. Shortly before its release, however, Microsoft decided to rename it Visual Studio .NET to highlight this new environment's relationship to .NET.
That sounded like a marketing ploy to me until I started delving into it. Visual Studio .NET differed quite a bit from its predecessors - enough so to warrant a new name. Visual Studio 2005 is the successor to the original Visual Studio .NET. (See Bonus Chapter 4 on the CD for a tour of some of Visual Studio's more potent features.)
Microsoft calls its implementation of the language Visual C#. In reality, Visual C# is nothing more than the C# component of Visual Studio. C# is C#, with or without the Visual Studio.
Okay, that's it. No more questions.
Creating a Windows Application with C#
To help you get your feet wet with C# and Visual Studio, this section takes you through the steps for creating a simple Windows program. Windows programs are commonly called Windows applications, WinApps or WinForms apps for short.
Because this book focuses on the C# language, it's not a Web-programming book, a database book, or a Windows programming book per se. In particular, this chapter constitutes the only coverage of Windows Forms visual programming. All I have room to do is give you this small taste.
In addition to introducing Windows Forms, this program serves as a test of your Visual Studio environment. This is a test; this is only a test. Had it been an actual Windows program ... Wait, it is an actual Windows program. If you can successfully create, build, and execute this program, your Visual Studio environment is set up properly, and you're ready to rock.
Creating the template
Writing Windows applications from scratch is a notoriously difficult process. With numerous session handles, descriptors, and contexts, creating even a simple Windows program poses innumerable challenges.
Visual Studio 2005 in general and C# in particular greatly simplify the task of creating your basic WinApp. To be honest, I'm a little disappointed that you don't get to go through the thrill of doing it by hand. In fact, why not switch over to Visual C++ and ... okay, bad idea.
Because Visual C# is built specifically to execute under Windows, it can shield you from many of the complexities of writing Windows programs from scratch. In addition, Visual Studio 2005 includes an Applications Wizard that builds template programs.
Typically, template programs don't actually do anything - at least, not anything useful (sounds like most of my programs). However, they do get you beyond that initial hurdle of getting started. Some template programs are reasonably sophisticated. In fact, you'll be amazed at how much capability the App Wizard can build on its own.
After you've completed the Visual Studio 2005 installation, follow these steps to create the template:
1. To start Visual Studio, choose Start [right arrow] All Programs [right arrow] Microsoft Visual Studio 2005 [right arrow] Microsoft Visual Studio 2005, as shown in Figure 1-1.
After some gnashing of CPU teeth and thrashing of disk, the Visual Studio desktop appears. Now things are getting interesting.
2. Choose File [right arrow] New [right arrow] Project, as shown in Figure 1-2.
Visual Studio responds by opening the New Project dialog box, as shown in Figure 1-3.
A project is a collection of files that Visual Studio builds together to make a single program. You'll be creating C# source files, which carry the extension .CS. Project files use the extension .CSPROJ.
3. Under Project Types, select Visual C#, and under that, click Windows. Under Templates, click Windows Application.
If you don't see the correct template icon right away, don't panic - you may need to scroll around in the Templates pane a bit.
Don't click OK, yet.
4. In the Name text box, enter a name for your project, or use the default name.
The Application Wizard will create a folder in which it stores various files, including the project's initial C# source file. The Application Wizard uses the name you enter in the Name text box as the name of that folder. The initial default name is WindowsApplication1. If you've been here before, the default name may be WindowsApplication2, WindowsApplication3, and so on.
For this example, you can use the default name and the default location for this new folder: My Documents\Visual Studio Projects\ WindowsApplication1. I put my real code there too, but for this book, I've changed the default location to a shorter file path. To change the default location, choose Tools[right arrow]Options[right arrow]Projects and Solutions[right arrow]General. Select the new location - C:\C#Programs for this book - in the Visual Studio Projects Location box, and click OK. (You can create the new directory in the Project Location dialog box at the same time. Click the folder icon with a small sunburst at the top of the dialog box. The directory may already exist if you've installed the example programs from the CD.)
5. Click OK.
The Application Wizard makes the disk light blink for a few seconds before opening a blank Form1 in the middle of the display.
Building and running your first Windows Forms program
After the Application Wizard loads the template program, Visual Studio opens the program in Design mode. You should convert this empty C# source program into a Windows Application, just to make sure that the template the Application Wizard generated doesn't have any errors.
The act of converting a C# source file into a living, breathing Windows Application is called building (or compiling). If your source file has any errors, Visual C# will find them during the build process.
To build and run your first Windows Forms program, follow these steps:
1. Choose Build[right arrow]Build projectname (where projectname is a name like WindowsApplication1 or MyProject).
The Output window may open. If not, you can open it before you build if you like. Choose View [right arrow] Other Windows[right arrow]Output. Then Build. In the Output window, a set of messages scrolls by. The last message in the Output window should be Build: 1 succeeded, 0 failed, 0 skipped (or something very close to that). This is the computer equivalent of "No runs, no hits, no errors." If you don't bother with the Output window, you should see Build succeeded or Build failed in the status bar just above the Start menu.
Figure 1-4 shows what Visual Studio looks like after building the default Windows program, complete with Output window. Don't sweat the positions of the windows. You can move them around as needed. The important parts are the Forms Designer window and the Output window. The designer window's tab is labeled "Form1.cs [Design]."
2. You can now execute this program by choosing Debug [right arrow] Start Without Debugging.
The program starts and opens a window that looks just like the one in the Forms Designer window, as shown in Figure 1-5.
In C# terms, this window is called a form. A form has a border and a title bar across the top with the little Minimize, Maximize, and Close buttons.
3. Click the little Close button in the upper-right corner of the frame to terminate the program.
See! C# programming isn't so hard.
As much as anything, this initial program is a test of your installation. If you've gotten this far, your Visual Studio is in good shape and ready for the programs throughout the rest of this book.
Excerpted from C# 2005 For Dummies by Stephen Randy Davis Excerpted by permission.
All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.
Table of Contents
Part I: Creating Your First C# Programs.
Chapter 1: Creating Your First C# Windows Program.
Chapter 2: Creating Your First C# Console Application.
Part II: Basic C# Programming.
Chapter 3: Living with Variability — Declaring Value-Type Variables.
Chapter 4: Smooth Operators.
Chapter 5: Controlling Program Flow.
Part III: Object-Based Programming.
Chapter 6: Collecting Data — The Class and the Array.
Chapter 7: Putting on Some High-Class Functions.
Chapter 8: Class Methods.
Chapter 9: Stringing in the Key of C#.
Part IV: Object-Oriented Programming.
Chapter 10: Object-Oriented Programming — What’s It All About?
Chapter 11: Holding a Class Responsible.
Chapter 12: Inheritance — Is That All I Get?
Chapter 13: Poly-what-ism?
Part V: Beyond Basic Classes.
Chapter 14: When a Class Isn’t a Class — The Interface and the Structure.
Chapter 15: Asking Your Pharmacist about Generics.
Part VI: The Part of Tens.
Chapter 16: The 10 Most Common Build Errors (And How to Fix Them).
Chapter 17: The 10 Most Significant Differences between C# and C++.
Appendix: About the CD.
Bonus Chapters on the CD-ROM!
Bonus Chapter 1: Some Exceptional Exceptions.
Bonus Chapter 2: Handling Files and Libraries in C#.
Bonus Chapter 3: Stepping through Collections.
Bonus Chapter 4: Using the Visual Studio Interface.
Bonus Chapter 5: C# on the Cheap.
End-User License Agreement.