Microsoft & .NET.NETProgramming with C# - - 101

Programming with C# – – 101

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Preparing to Program

You should take certain steps when you’re solving a problem. First, you must define the problem. If you don’t know what the problem is, you can’t find a solution! After you know what the problem is, you can devise a plan to fix it. When you have a plan, you can usually implement it. After the plan is implemented, you must test the results to see whether the problem is solved. This same logic can be applied to many other areas, including programming.

When creating a program in C# (or in any language), you should follow a similar sequence of steps:

  1. Determine the objective(s) of the program.
  2. Determine the methods you want to use in writing the program.
  3. Create the program to solve the problem.
  4. Run the program to see the results.

An example of an objective (see step 1) might be to write a word processor or database program. A much simpler objective is to display your name on the screen. If you don’t have an objective, you won’t be able to write an effective program.

The second step is to determine the method you want to use to write the program. Do you need a computer program to solve the problem? What information needs to be tracked? What formulas will be used? During this step, you should try to determine what will be needed and in what order the solution should be implemented.

As an example, assume that someone asks you to write a program to determine the area inside a circle. Step 1 is complete, because you know your objective: Determine the area inside a circle. Step 2 is to determine what you need to know to ascertain the area. In this example, assume that the user of the program will provide the radius of the circle. Knowing this, you can apply the formula r2 to obtain the answer. Now you have the pieces you need, so you can continue to steps 3 and 4, which are called the Program Development Cycle.

The Program Development Cycle

The Program Development Cycle has its own steps. In the first step, you use an editor to create a file containing your source code. In the second step, you compile the source code to create an intermediate file called either an executable file or a library file. The third step is to run the program to see whether it works as originally planned.

Creating the Source Code

Source code is a series of statements or commands that are used to instruct the computer to perform your desired tasks. As mentioned, the first step in the Program Development Cycle is to enter source code into an editor. For example, here is a line of C# source code:

System.Console.WriteLine("Hello, Mom!");

This statement instructs the computer to display the message Hello, Mom! onscreen. (For now, don’t worry about how this statement works.)

Using an Editor

An editor is a program that can be used to enter and save source code. There are a number of editors that can be used with C#. Some are made specifically for C#, and others are not.

At the time this book was written, there were only a few editors created for C#; however, as time goes on, there will be many more. Microsoft has added C# capabilities to its Visual Studio product which includes Visual C#. This is the most predominant editor available. If you don’t have Visual Studio .NET, however, you can still do C# programming.

There are also other editors available for C#. Like Visual Studio .NET, many of these enable you to do all the steps of the development cycle without leaving the editor. More importantly, most of these color-code the text you enter. This makes it much easier to find possible mistakes. Many editors will even help you by given you information on what you need to enter and giving you a robust help system.

If you don’t have a C# editor, don’t fret. Most computer systems include a program that can be used as an editor. If you’re using Microsoft Windows, you can use either Notepad or WordPad as your editor. If you’re using a Linux or UNIX system, you can use such editors as ed, ex, edit, emacs, or vi.

Most word processors use special codes to format their documents. Other programs can’t read these codes correctly. Many word processors[md]such as WordPerfect, Microsoft Word, and WordPad – are capable of saving source files in a text-based form. When you want to save a word processor’s file as a text file, select the text option when saving.

To find alternative editors, you can check computer stores or computer mail-order catalogs. Another place to look is in the ads in computer programming magazines. The following are a few editors that were available at the time this book was written:

  • CodeWright. CodeWright is an editor that provides special support for ASP, XML, HTML, C#, Perl, Python, and more. It is located at www.premia.com.
  • EditPlus. EditPlus is an Internet-ready text editor, HTML editor, and programmer’s editor for Windows. Although it can serve as a good replacement for Notepad, it also offers many powerful features for Web page authors and programmers, including the color-coding of code. It is located at www.editplus.com.
  • JEdit. JEdit is an Open-Source editor for Java; however, it can be used for C#. It includes the capability of color-coding the code. It is located at http://jedit.sourceforge.net.
  • Poorman IDE by Duncan Chen. Poorman provides a syntax-highlighted editor for both C# and Visual Basic .NET. It also enables you to run the compiler and capture the console output so you don’t need to leave the Poorman IDE. Poorman is located at www.geocities.com/duncanchen/poormanide.htm.
  • SharpDevelop. SharpDevelop is a free editor for C# projects on Microsoft’s NET platform. It is an Open-Source Editor (GPL), so you can download both source code and executables from www.icsharpcode.net.

Naming Your Source Files

When you save a source file, you must give it a name that describes what the program does. In addition, when you save C# program source files, give the file a .cs extension. Although you could give your source file any name and extension, .cs is recognized as the appropriate extension to use.

Executing a C# Program

Before digging into the Program Development Cycle, it is important to understand a little bit about how a C# program executes. C# programs are different from programs you could create with other programming languages.

C# programs are created to run on the Common Language Runtime (CLR). This means that if you create a C# executable program and try to run it on a machine that doesn’t have the CLR or a compatible runtime, it won’t execute.

The benefit of creating programs for a runtime environment is portability. In older languages such as C and C++, if you wanted to create a program that could run on different platforms or operating systems, you had to compile different executable programs. For example, if you wrote a C application and you wanted to run it on a Linux machine and a Windows machine, you would have to create two executable programs[md]one on a Linux machine and one on a Windows machine. With C#, you create only one executable program, and it runs on either machine.

If you want your program to execute as fast as possible, you want to create a true executable. A computer requires digital, or binary, instructions in what is called machine language. A program must be translated from source code to machine language. A program called a compiler performs this translation. The compiler takes your source code file as input and produces a disk file containing the machine language instructions that correspond to your source code statements. With programs such as C and C++, the compiler creates a file that can be executed with no further effort.

With C#, you use a compiler that does not produce machine language. Instead it produces an Intermediate Language (IL) file. Because this isn’t directly executable by the computer, you need something more to happen to translate or further compile the program for the computer. The CLR or a compatible C# runtime does this final compile just as it is needed.

One of the first things the CLR does with an IL file is a final compile of the program. In this process, the CLR converts the code from the portable, IL code to a language (machine language) that the computer can understand and run. The CLR actually compiles only the parts of the program that are being used. This saves time. Additionally, after a portion of your IL file has been given a true compile on a machine, it never needs to be compiled again, because the final compiled portion of the program is saved and used the next time that portion of the program is executed.

Compiling C# Source Code

To create the IL file, you use the C# compiler. You typically use the csc command to run the compiler, followed by the name of the source file. For example, to compile a source file called radius.cs, you type the following at the command line:

csc radius.cs

If you’re using a graphical development environment, compiling is even simpler. In most graphical environments, you can compile a program by selecting the compile icon or selecting the appropriate option from the menu. After the code is compiled, selecting the run icon or selecting the appropriate option from the menus executes the program. You should check your compiler’s manuals for specifics on compiling and running a program.

After you compile, you have an IL file. If you look at a list of the files in the directory or folder in which you compiled, you should find a new file that has the same name as your source file, but with an .exe (rather than a .cs) extension. The file with the .exe extension is your “compiled” program (called an assembly). This program is ready to run on the CLR. The assembly file contains all the information that the common runtime needs to know to execute the program.

Figure 1.1 shows the progression from source code to executable.

Figure 1.1.The C# source code that you write is converted to Intermediate Language (IL) code by the compiler.

Completing the Development Cycle

After your program is a compiled IL file, you can run it by entering its name at the command-line prompt or just as you would run any other program.

If you run the program and receive results different from what you thought you would, you need to go back to the first step of the development process. You must identify what caused the problem and correct it in the source code. When you make a change to the source code, you need to recompile the program to create a corrected version of the executable file. You keep following this cycle until you get the program to execute exactly as you intended.

Figure 1.2 shows the program development steps. For all but the simplest programs, you might go through this sequence many times before finishing your program. Even the most experienced programmers can’t sit down and write a complete, error-free program in just one step! Because you’ll be running through the edit-compile-test cycle many times, it’s important to become familiar with your tools: the editor, compiler, and runtime environment.

Figure 1.2.The steps involved in C# program development.

Your First C# Program

You’re probably eager to try your first program in C#. To help you become familiar with your compiler, Listing 1.1 contains a quick program for you to work through. You might not understand everything at this point, but you should get a feel for the process of writing, compiling, and running a real C# program.

This demonstration uses a program named hello.cs, which does nothing more than display the words Hello, World! On the screen. This program is the traditional program used to introduce people to programming. It is also a good one for you to use to learn. The source code for hello.cs is in Listing 1.1. When you type this listing, don’t include the line numbers on the left or the colons.

Listing 1.1. hello.cs

1:  class Hello2:  {3:     static void Main() 4:     {5:        System.Console.WriteLine("Hello, World!");6:     }7:  }

Be sure that you have installed your compiler as specified in the installation instructions provided with the software. When your compiler and editor are ready, follow the steps in the next section to enter, compile, and execute hello.cs.

In order to create a C# program you will need a C# compiler. Microsoft includes a C# compiler with its .NET Framework. The .NET Framework can be downloaded from the Microsoft site (http://www.microsoft.com/net/downloads.asp).

Entering and Compiling hello.cs

To enter and compile the hello.cs program, follow these steps:

  1. Start your editor.
  2. Use the keyboard to type the hello.cs source code shown in Listing 1.1. Don’t enter the line numbers or colons. These are provided only for reference within this book. Press Enter at the end of each line. Make sure that you enter the code using the same case. C# is case sensitive, so if you change the capitalization, you will get errors.
    If you are a C or C++ programmer, you will most likely make a common mistake. In C and C++, main() is lowercase. In C#, Main() has a capital M. In C#, if you type a lowercase m, you will get an error.

  3. Save the source code. You should name the file hello.cs.
  4. Verify that hello.cs has been saved by listing the files in the directory or folder.
  5. Compile hello.cs. If you are using the command-line compiler, enter the following:

    csc hello.cs

    If you are using an Integrated Development Environment, select the appropriate icon or menu option. You should get a message stating that there were no errors or warnings.

  6. Check the compiler messages. If you receive no errors or warnings, everything should be okay.

    If you made an error typing the program, the compiler will catch it and display an error message. For example, if you misspelled the word Console as Consol, you would see a message similar to the following:

    hello.cs(5,7): error CS0117: 'System' does not contain      a definition for 'Consol'

  7. Go back to step 2 if this or any other error message is displayed. Open the hello.cs file in your editor. Compare your file’s contents carefully with Listing 1.1, make any necessary corrections, and continue with step 3.
  8. Your first C# program should now be compiled and ready to run. If you display a directory listing of all files named hello (with any extension), you should see the following:

    hello.cs, the source code file you created with your editorhello.exe, the executable program created when you compiled hello.cs

  9. To execute, or run, hello.exe, enter hello at the command line. The message Hello, World! is displayed onscreen.
If you run the hello program by double-clicking in Microsoft’s Windows Explorer, you might not see the results. This program runs in a command-line window. When you double-click in Windows Explorer, the program opens a command-line window, runs the program, and[md]because the program is done – closes the window. This can happen so fast that it doesn’t seem that anything happens. It is better to open a command-line window, change to the directory containing the program, and then run the program from the command line.

Congratulations! You have just entered, compiled, and run your first C# program. Admittedly, hello.cs is a simple program that doesn’t do anything useful, but it’s a start. In fact, most of today’s expert programmers started learning in this same way – by compiling a “hello world” program.

This article is brought to you by Sams Publishing and Bradley L. Jones.
This article is an excerpt from Sams Teach Yourself C# in 21 Days
© Copyright Bradley L. Jones, All Rights Reserved
 

# # #

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories