|
|
Getting Started With C# By Herbert Schildt
C# is a language specifically designed and optimized for Microsoft's .NET Framework. Its chief architect was long time programming guru Anders Hejlsberg. C# is directly descended from C++, from which it derives many of its features, including its syntax, keywords, and object model. It is also closely related to Java. For example, both C# and Java manage memory through garbage collection. In addition to the features that it inherits from C++ and Java, C# adds several of its own innovations, such as delegates and indexers. If .NET development is in your future, then C# is the right language to learn. The purpose of this article is to help you take your first steps toward becoming a C# programmer. Here you will learn how to
Keep in mind that C# is a professional programming language designed to support the rich computing environment of .NET. As a result, C# is quite large. The information presented here is only a starting point. Note: Before you can compile and run C# programs, you must have a C# compiler installed on your computer. The primary development environment for C# is Microsoft's Visual Studio .NET.
Create, Compile, and Run Your First C# Program The first step to learning to program in C# is to understand how to compile and run a C# program. The one we will begin with is shown here. /* Here is the sequence you will follow.
Enter the Program When you write a program, you create a file that contains the program's source code. Source code is the human-readable form of a program. Thus, you must begin by creating a file that holds the source code to the program just shown. To enter the program, you must use a text editor, not a word processor. Word processors typically store format information along with text. This format information will confuse the C# compiler. If you are using Windows you can use WordPad to enter the program. Just be sure to save it as a text file. Of course, if you are using Visual Studio, then you can use the built-in editor to enter the program. The name of the file that holds the source code for a C# program is technically arbitrary. However, C# programs are normally contained in files that use the extension .cs. Thus, you can call a C# program file by any name, but it should use the .cs extension. For this first example, name the source file Example.cs so that you can follow along with the instructions for compiling and running the program.
Compile the Program Before you can run the program, you must compile it. Compilation translates the source code into a form that can be executed. In the case of C#, the output of the compiler is MSIL, which stands for Microsoft Intermediate Language. MSIL defines a set of portable instructions that are independent of any specific CPU. MSIL is executed by the Common Language Runtime (CLR). The CLR provides a just-in-time (JIT) compiler that translates MSIL into executable code when the program is run. Visual Studio provides two different ways to compile a program: the command-line compiler and the Integrated Development Environment (IDE). Although the IDE is excellent for developing real world applications, the command-line compiler is much easier to use when compiling short, sample programs such as those shown in this article. Therefore, it is the method described here. Before using the command-line compiler, you must execute the batch file VCVARS32.BAT, which is provided by Visual Studio (in its BIN directory). This batch file configures a command-prompt session for use with the command-line compiler. Alternatively, you can start a command-prompt session already configured for Visual C# by choosing Visual Studio .NET Command Prompt from the list of tools shown under the Visual Studio .NET entry in the Start | Programs menu of the task bar. To compile the program, execute the C# compiler, csc.exe, specifying the name of the source file on the command line, as shown here: csc Example.cs The csc compiler creates a file called Example.exe that contains the MSIL version of the program. Although MSIL is not executable code, it is still contained in an exe file. As explained, the CLR automatically invokes the JIT compiler when you execute Example.exe. Be aware, however, that if you try to execute Example.exe (or any other exe file that contains MSIL) on a computer for which the .NET Framework is not installed, the program will not execute, because the CLR will be missing.
Run the Program To actually run the program, just type its name on the command line, as shown here: Example When the program is run, the following output is displayed: A simple C# program.
The First Sample Program Line by Line Although Example.cs is quite short, it includes several key features that are common to all C# programs. Let's closely examine each part of the program. The program begins with the following lines: /* This is a comment. Like most other programming languages, C# lets you enter remarks into a program’s source file. The contents of a comment are ignored by the compiler. Instead, a comment describes or explains the operation of the program to anyone who is reading its source code. In this case, the comment describes the program and suggests that you call the source file Example.cs. Of course, in real applications, comments generally explain how some part of the program works or what a specific feature does. C# supports three styles of comments. Two types are used in the program: multiline and single-line. (The third type is the documentation comment, but it is beyond the scope of this article.) The one shown at the top of the program is called a multiline comment. This type of comment must begin with /* and end with */. Anything between these two comment symbols is ignored by the compiler. As the name suggests, a multiline comment can be several lines long. The next line in the program is using System; This line indicates that the program is using the System namespace. In C#, a namespace defines a declarative region. Names declared in one namespace are separate from names declared in another. Thus, namespaces prevent name conflicts. The namespace used by the program is System, which is the namespace reserved for items associated with the .NET Framework. The using keyword simply states that the program is using the names in the given namespace. The next line of code in the program is shown here. class Example { This line uses the keyword class to declare that a new class is being defined. The class defines a basic unit of program functionality. All program activity occurs in a class, and all programs must define at least one class. Example is the name of the class. The class definition begins with the opening curly brace { and ends with the closing curly brace }. The elements between the two braces are members of the class. The next line in the program is the single-line comment, shown here. // A C# program begins with a call to Main(). This is the second type of comment supported by C#. A single-line comment begins with a // and ends at the end of the line. As a general rule, programmers use multiline comments for longer remarks and single-line comments for brief, line-by-line descriptions. The next line of code is static void Main() { This line begins the Main( ) method. In C#, a subroutine is called a method. As the comment preceding it suggests, this is the line at which the program will begin executing. All C# programs begin execution by calling Main( ). The keyword static allows Main( ) to be called before an object of its class has been created. This is necessary since Main( ) is called at program startup. The keyword void simply tells the compiler that Main( ) does not return a value. The last character on the line is the {. This signals the start of Main( )’s body. All of the code that comprises a method will occur between the method’s opening curly brace and its closing curly brace. The next line of code is shown here. Notice that it occurs inside Main( ). Console.WriteLine("A simple C# program."); This line outputs the string "A simple C# program." followed by a new line on the screen. Output is actually accomplished by the built-in method WriteLine( ). In this case, WriteLine( ) displays the string that is passed to it. In addition to strings, WriteLine( ) can be used to display other types of information, too. The line begins with Console, which is the name of a predefined class that handles console I/O. By connecting Console with WriteLine( ), you are telling the compiler that WriteLine( ) is a member of the Console class. Notice that this statement ends with a semicolon. In general, all C# statements end with a semicolon. The first } in the program ends Main( ), and the last } ends the Example class definition. One last point: C# is case-sensitive. Forgetting this can cause problems. For example, if you accidentally type main instead of Main, or writeline instead of WriteLine, the preceding program will be incorrect. Furthermore, if you misspell Main, the compiler will still compile your program. However, when you try to run the program, you will see an error message that states that Example.exe does not have an entry point defined.
Using a Variable Perhaps no other construct is as important to a programming language as the assignment of a value to a variable. A variable is a named memory location that can be assigned a value. Further, the value of a variable can be changed during the execution of a program. That is, the content of a variable is changeable, not fixed. The following program creates two variables called x and y: // This program demonstrates variables. When you run this program, you will see the following output: x contains 10 This program introduces several new concepts. First, the statement int x; // this declares a variable called x declares a variable called x of type integer. In C#, all variables must be declared before they are used. Further, the kind of values that the variable can hold must also be specified. This is called the type of the variable. In this case, x can hold integer values. These are whole numbers. In C#, to declare a variable to be of type integer, precede its name with the keyword int. Thus, the preceding statement declares a variable called x of type int. The next line declares a second variable called y. int y; // this declares a variable called y Notice that its uses the same format as the first except that the name of the variable is different. In general, to declare a variable you will use a statement like this:
Here, type specifies the type of variable being declared, and var-name is the name of the variable. In addition to int, C# supports several other data types, such as char, short, decimal, double, and float. In C#, variable names (and other programmer-defined names) are called identifiers. Identifiers may start with any letter of the alphabet or an underscore. Next may be either a letter, a digit, or an underscore. The underscore can be used to enhance the readability of a variable name, as in line_count. Uppercase and lowercase are different; that is, myvar and MyVar are separate names. Here are some examples of acceptable identifiers:
Remember, you can't start an identifier with a digit. Thus, 12x is invalid, for example. The next line in the program, shown here, assigns x the value 10. x = 10; // this assigns 10 to x In C#, the assignment operator is the single equal sign. It copies the value on its right side into the variable on its left. The next line of code outputs the value of x preceded by the string "x contains ". Console.WriteLine("x contains " + x); In this statement, the plus sign causes the value of x to be displayed after the string that precedes it. This approach can be generalized. Using the + operator, you can chain together as many items as you want within a single WriteLine( ) statement. The next line of code assigns y the value of x plus 2. y = x + 2; // this assigns to y the value of x + 2 After the line executes, y will contain the value 12. The value of x is unchanged and is still 10. Like most other computer languages, C# supports a full range of arithmetic operators, including those shown here:
Here is the last line in the program: Console.WriteLine("y contains " + y); It displays the string "y contains " followed by the value of y, which is 12.
Two Control Statements Inside a method, execution proceeds sequentially from one statement to the next, top to bottom. It is possible, however, to alter this flow through the use of the various program control statements. C# supports a rich set of such statements. We will examine two here: the if and for.
The if Statement You can selectively execute part of a program through the use of C#’s conditional statement: the if. Its simplest form is shown here:
Here, condition is an expression that evaluates to either true or false. If condition is true, then the statement is executed. If condition is false, then the statement is bypassed. Here is an example: if(10 < 11) Console.WriteLine("10 is less than 11"); In this case, since 10 is less than 11, the conditional expression is true, and WriteLine( ) will execute. However, consider the following: if(10 < 9) Console.WriteLine("this won't be displayed"); In this case, 10 is not less than 9. Thus, the call to WriteLine( ) will not take place. C# defines a full complement of relational operators that can be used in a conditional expression. They are shown here.
Notice that the test for equality is the double equal sign. Here is a program that illustrates the if statement: // Demonstrate the if. The output generated by this program is shown here: a is not equal to b
The for Loop You can repeatedly execute a sequence of code by creating a loop. C# supplies a rich assortment of loop constructs. The one we will look at here is the for loop. The simplest form of the for loop is shown here:
The initialization portion of the loop sets a loop control variable to an initial value. The condition is an expression that tests the loop control variable. If the outcome of that test is true, statement is executed and the loop keeps running. If it is false, the loop terminates. The itr-expr expression determines how the loop control variable is changed each time the loop iterates. The following program demonstrates the for. It prints the numbers 0 through 4 on the screen. // Demonstrate the for loop. The output generated by the program is shown here: This is x: 0 In this example, x is the loop control variable. It is set to zero in the initialization portion of the for. At the start of each iteration (including the first one), the conditional test x < 5 is performed. If the outcome of this test is true, the WriteLine( ) statement is executed, and then x is increased by 1. This process continues until the conditional test is false, at which point execution picks up at the bottom of the loop. As a point of interest, in professionally written C# programs you will almost never see the iteration expression of the loop written as shown in the preceding program. That is, you will seldom see statements like this: x = x + 1; The reason is that C# includes a special increment operator that performs this operation more efficiently. The increment operator is ++ (that is, two plus signs back to back). The increment operator increases its operand by one. By use of the increment operator, the preceding statement can be written like this: x++; Thus, the for in the preceding program will usually be written like this: for(x = 0; x < 5; x++) You might want to try this. As you will see, the loop still runs exactly the same as it did before. C# also provides a decrement operator, which is specified as – –. This operator decreases its operand by one.
Using Blocks of Code Another key element of C# is the code block. A code block is a grouping of two or more statements. This is done by enclosing the statements between opening and closing curly braces. Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can. For example, a block can be a target for if and for statements. Consider this if statement: if(w < h) { Here, if w is less than h, then both statements inside the block will be executed. Thus, the two statements inside the block form a logical unit, and one statement cannot execute without the other also executing. The key point here is that whenever you need to logically link two or more statements, you do so by creating a block.
Putting It All Together Although you know only a little about C# at this point, you can still use it to write a useful program. The following program creates a table of temperature conversions from Fahrenheit to Celsius, beginning with 0 degrees and ending at 99. This is accomplished through the use of a for loop. After every 10 conversions, it outputs a blank line. This is handled by an if statement that examines the value of a variable called count. After each conversion is displayed, the value of count is incremented. If it equals 10, a blank line is output and count is reset. Notice that the targets of the for and if are blocks of code. /* Here is a portion of the output. 0 degrees Fahrenheit is -17.76 degrees Celsius. 1 degrees Fahrenheit is -17.205 degrees Celsius. 2 degrees Fahrenheit is -16.65 degrees Celsius. 3 degrees Fahrenheit is -16.095 degrees Celsius. 4 degrees Fahrenheit is -15.54 degrees Celsius. 5 degrees Fahrenheit is -14.985 degrees Celsius. 6 degrees Fahrenheit is -14.43 degrees Celsius. 7 degrees Fahrenheit is -13.875 degrees Celsius. 8 degrees Fahrenheit is -13.32 degrees Celsius. 9 degrees Fahrenheit is -12.765 degrees Celsius. 10 degrees Fahrenheit is -12.21 degrees Celsius. 11 degrees Fahrenheit is -11.655 degrees Celsius. 12 degrees Fahrenheit is -11.1 degrees Celsius. 13 degrees Fahrenheit is -10.545 degrees Celsius. 14 degrees Fahrenheit is -9.99 degrees Celsius. 15 degrees Fahrenheit is -9.435 degrees Celsius. 16 degrees Fahrenheit is -8.88 degrees Celsius. 17 degrees Fahrenheit is -8.325 degrees Celsius. 18 degrees Fahrenheit is -7.77 degrees Celsius. 19 degrees Fahrenheit is -7.215 degrees Celsius.
A Short Word About Object-Oriented Programming As explained earlier, the class is C#'s basic unit of program functionality. However, it is more than that. It is also C#'s foundation for object-oriented programming (OOP). Although C#'s object-oriented features are beyond the scope of this article, they are an important part of C# programming because C# is an object-oriented programming language. OOP is based on three key principles: encapsulation, inheritance, and polymorphism. Encapsulation binds together code and data, inheritance is the mechanism by which one class can inherit the functionality of another, and polymorphism lets you define one interface that describes a general set of actions. These attributes work together in a powerful way that enables the construction of reliable, reusable, and extensible programs. As you advance in your study of C#, you will see how the object-oriented features play an integral role in the way that C# code is written.
Continuing Your Study of C# This short introduction to C# has shown you some of the key elements of the language, including the general form of a program, variables, two control statements, and code blocks. Of course, only a very small part of C# has been described. To continue learning about C#, consider C#: A Beginner's Guide. |
|