C H A P T E R  2

Overview of C# Programming

A Simple C# Program

This chapter lays the groundwork for studying C#. Since I’ll use code samples extensively throughout the text, I first need to show you what a C# program looks like and what its various parts mean.

I’ll start by demonstrating a simple program and explaining its components one by one. This will introduce a range of topics, from the structure of a C# program to the method of producing program output to the screen.

With these source code preliminaries out of the way, I can then use code samples freely throughout the rest of the text. So, unlike the following chapters, where one or two topics are covered in detail, this chapter touches on many topics with only a minimum of explanation.

Let’s start by looking at a simple C# program. The complete source code of the program is shown in the shaded area at the top left of Figure 2-1. As shown, the code is contained in a text file called SimpleProgram.cs. As you read through it, don’t worry about understanding all the details. Table 2-1 gives a line-by-line description of the code. The shaded area at the bottom left of the figure shows the output of the program. The right-hand part of the figure is a graphical depiction of the parts of the program.

  • When the code is compiled and executed, it displays the string “Hi there!” in a window on the screen.
  • Line 5 contains two contiguous slash characters. These characters—and everything following them on the line—are ignored by the compiler. This is called a single-line comment.
Image

Figure 2-1. The SimpleProgram program

Image

More About SimpleProgram

A C# program consists of one or more type declarations. Much of this book is spent explaining the different types that you can create and use in your programs. The types in a program can be declared in any order. In the SimpleProgram example, only a class type is declared.

A namespace is a set of type declarations associated with a name. SimpleProgram uses two namespaces. It creates a new namespace called Simple, in which it declares its type (class Program), and uses the Console class defined in a namespace called System.

To compile the program, you can use Visual Studio or the command-line compiler. To use the command-line compiler, in its simplest form, use the following command in a command window:

   csc SimpleProgram.cs

In this command, csc is the name of the command-line compiler, and SimpleProgram.cs is the name of the source file. CSC stands for “C-Sharp Compiler.”

Identifiers

Identifiers are character strings used to name things such as variables, methods, parameters, and a host of other programming constructs that will be covered later.

You can create self-documenting identifiers by concatenating meaningful words into a single descriptive name, using uppercase and lowercase letters (e.g., CardDeck, PlayersHand, FirstName, SocialSecurityNum). Certain characters are allowed or disallowed at certain positions in an identifier. Figure 2-2 illustrates these rules.

  • The alphabetic and underscore characters (a through z, A through Z, and _) are allowed at any position.
  • Digits are not allowed in the first position but are allowed everywhere else.
  • The @ character is allowed in the first position of an identifier but not at any other position. Although allowed, its use is generally discouraged.
Image

Figure 2-2. Characters allowed in identifiers

Identifiers are case-sensitive. For instance, the variable names myVar and MyVar are different identifiers.

As an example, in the following code snippet, the variable declarations are all valid and declare different integer variables. But using such similar names will make coding more error-prone and debugging more difficult. Those debugging your code at some later time will not be pleased.

   // Valid syntactically, but very confusing!
   int totalCycleCount;
   int TotalCycleCount;
   int TotalcycleCount;

I’ll describe the recommended C# naming conventions in Chapter 7.

Keywords

Keywords are the character string tokens used to define the C# language. Table 2-2 gives a complete list of the C# keywords.

Some important things to know about keywords are the following:

  • Keywords cannot be used as variable names or any other form of identifier, unless prefaced with the @ character.
  • All C# keywords consist entirely of lowercase letters. (.NET type names, however, use Pascal casing.)

Image

Contextual keywords are identifiers that act as keywords only in certain language constructs. In those positions, they have particular meanings; but unlike keywords, which cannot ever be used as identifiers, contextual keywords can be used as identifiers in other parts of the code. Table 2-3 contains the list of contextual keywords.

Image

Main: The Starting Point of a Program

Every C# program must have one class with a method called Main. In the SimpleProgram program shown previously, it was declared in a class called Program.

  • The starting point of execution of every C# program is at the first instruction in Main.
  • The name Main must be capitalized.

The simplest form of Main is the following:

    static void Main( )
    {
       Statements
    }

Whitespace

Whitespace in a program refers to characters that do not have a visible output character. Whitespace in source code is ignored by the compiler, but is used by the programmer to make the code clearer and easier to read. Some of the whitespace characters include the following:

  • Space
  • Tab
  • New line
  • Carriage return

For example, the following code fragments are treated exactly the same by the compiler in spite of their differences in appearance.

   // Nicely formatted
   Main()
   {
      Console.WriteLine("Hi, there!");
   }
   
   // Just concatenated
   Main(){Console.WriteLine("Hi, there!");}

Statements

The statements in C# are very similar to those of C and C++. This section introduces the general form of statements; the specific statement forms are covered in Chapter 9.

A statement is a source code instruction describing a type or telling the program to perform an action.

  • A simple statement is terminated by a semicolon.

For example, the following code is a sequence of two simple statements. The first statement defines an integer variable named var1 and initializes its value to 5. The second statement prints the value of variable var1 to a window on the screen.

   int var1 = 5;
   System.Console.WriteLine("The value of var1 is {0}", var1);

Blocks

A block is a sequence of zero or more statements enclosed by a matching set of curly braces; it acts as a single syntactic statement.

You can create a block from the set of two statements in the preceding example by enclosing the statements in matching curly braces, as shown in the following code:

   {
      int var1 = 5;
      System.Console.WriteLine("The value of var1 is {0}", var1);
   }

Some important things to know about blocks are the following:

  • You can use a block whenever the syntax requires a statement but the action you need requires more than one simple statement.
  • Certain program constructs require blocks. In these constructs, you cannot substitute a simple statement for the block.
  • Although a simple statement is terminated by a semicolon, a block is not followed by a semicolon. (Actually, the compiler will allow it, because it’s parsed as an empty statement—but it’s not good style.)
    {        Terminating semicolon
                                                       Terminating semicolon
       int var2 = 5;                                           
       System.Console.WriteLine("The value of var1 is {0}", var1);
    }
     ↑  No terminating semicolon

Text Output from a Program

A console window is a simple command prompt window that allows a program to display text and receive input from the keyboard. The BCL supplies a class called Console (in the System namespace), which contains methods for inputting and outputting data to a console window.

Write

Write is a member of the Console class. It sends a text string to the program’s console window. In its simplest form, Write sends a literal string of text to the window. The string must be enclosed in quotation marks—double quotes, not single quotes.

The following line of code shows an example of using the Write member:

   Console.Write("This is trivial text.");
                            
                       Output string

This code produces the following output in the console window:


This is trivial text.

Another example is the following code, which sends three literal strings to the program’s console window:

   System.Console.Write ("This is text1. ");
   System.Console.Write ("This is text2. ");
   System.Console.Write ("This is text3. ");

This code produces the output that follows. Notice that Write does not append a newline character after a string, so the output of the three statements runs together on a single line.

This is text1.  This is text2.  This is text3.
                                     
     First           Second           Third
    statement          statement          statement

WriteLine

WriteLine is another member of Console; it performs the same functions as Write but appends a newline character to the end of each output string.

For example, if you use the preceding code, substituting WriteLine for Write, the output is on separate lines:

   System.Console.WriteLine("This is text1.");
   System.Console.WriteLine("This is text2.");
   System.Console.WriteLine("This is text3.");

This code produces the following output in the console window:


This is text1.
This is text2.
This is text3.

The Format String

The general form of the Write and WriteLine statements can take more than a single parameter.

  • If there is more than a single parameter, the parameters are separated by commas.
  • The first parameter must always be a string and is called the format string. The format string can contain substitution markers.
    • A substitution marker marks the position in the format string where a value should be substituted in the output string.
    • A substitution marker consists of an integer enclosed in a set of matching curly braces. The integer is the numeric position of the substitution value to be used. The parameters following the format string are called substitution values. These substitution values are numbered, starting at 0.

The syntax is as follows:

   Console.WriteLine( FormatString, SubVal0, SubVal1, SubVal2, ... );

For example, the following statement has two substitution markers, numbered 0 and 1, and two substitution values, whose values are 3 and 6, respectively.

                                            Substitution  markers
                                                          
   Console.WriteLine("Two sample integers are {0} and {1}.", 3, 6);
                                                              
                                   Format string             Substitution values

This code produces the following output on the screen:


Two sample integers are 3 and 6.

Multiple Markers and Values

In C#, you can use any number of markers and any number of values.

  • The values can be used in any order.
  • The values can be substituted any number of times in the format string.

For example, the following statement uses three markers and only two values. Notice that value 1 is used before value 0 and that value 1 is used twice.

   Console.WriteLine("Three integers are {1}, {0} and {1}.", 3, 6);

This code produces the following output:


   Three integers are 6, 3 and 6.

A marker must not attempt to reference a value at a position beyond the length of the list of substitution values. If it does, it will not produce a compile error but a runtime error (called an exception).

For example, in the following statement there are two substitution values, with positions 0 and 1. The second marker, however, references position 2—which does not exist. This will produce a runtime error.

                                                Position 0    Position 1
                                                         
   Console.WriteLine("Two integers are {0} and {2}.", 3   6);    // Error!
                                                
                                      There is no position 2 value.

Formatting Numeric Strings

Throughout this text, the sample code will use the WriteLine method to display values. Usually, it will use the simple substitution marker, consisting only of curly braces surrounding an integer.

Many times, however, in your own code, you’ll want to present the output of a text string in a format more appropriate than just a plain number. You might, for instance, want to display a value as currency or as a fixed-point value with a certain number of decimal places. You can do these things by using format strings.

For example, the following code consists of two statements that print out the value 500. The first line prints out the number without any additional formatting. In the second line, the format string specifies that the number should be formatted as currency.

   Console.WriteLine("The value: {0}."  , 500);        // Print out number
   Console.WriteLine("The value: {0:C}.", 500);        // Format as currency
                                    
                             Format as currency

This code produces the following output:


The value: 500.
The value: $500.00.

The difference between the two statements is that the formatted item includes additional information in the format specifier. The syntax for a format specifier consists of three fields inside the set of curly braces: the index, the alignment specifier, and the format field. Figure 2-3 shows the syntax.

Image

Figure 2-3. Syntax for a format specifier

The first thing in the format specifier is the index. As you know, the index specifies which item from the list following the format string should be formatted. The index is required, and the numbering of the list items starts at 0.

The Alignment Specifier

The alignment specifier represents the minimum width of the field in terms of characters. The alignment specifier has the following characteristics:

  • The alignment specifier is optional and separated from the index with a comma.
  • It consists of a positive or negative integer.
    • The integer represents the minimum number of characters to use for the field.
    • The sign represents either right or left alignment. A positive number specifies right alignment; a negative number specifies left alignment.
          Index—use 0th item in the list
                      
   Console.WriteLine("{0, 10}", 500);
                           
    Alignment specifier—right-align in a field of ten characters

For example, the following code, which formats the value of int variable myInt, shows two format items. In the first case, the value of myInt is displayed as a right-aligned string of ten characters. In the second case, it’s left-aligned. The format items are between two vertical bars, just so that in the output you can see the limits of the string on each side.

   int myInt = 500;
   Console.WriteLine("|{0, 10}|", myInt);                 // Aligned right
   Console.WriteLine("|{0,-10}|", myInt);                 // Aligned left

This code produces the following output; there are ten characters between the vertical bars:


|       500|
|500       |

The actual representation of the value might take more or fewer characters than specified in the alignment specifier:

  • If the representation takes fewer characters than specified in the alignment specifier, the remaining characters are padded with spaces.
  • If the representation takes more characters than specified, the alignment specifier is ignored, and the representation uses as many characters as are needed.
The Format Field

The format field specifies the form that the numeric representation should take. For example, should it be represented as currency, in decimal format, in hexadecimal format, or in fixed-point notation?

The format field has three parts, as shown in Figure 2-4:

  • The colon character must be next to the format specifier, with no intervening spaces.
  • The format specifier is a single alphabetic character, from a set of nine built-in character formats. The character can be uppercase or lowercase. The case is significant for some specifiers but not for others.
  • The precision specifier is optional and consists of one or two digits. Its actual meaning depends on the format specifier.
Image

Figure 2-4. Standard format field string

The following code shows an example of the syntax of the format string component:

          Index—use 0th item in the list
                      
   Console.WriteLine("{0:F4}", 12.345678);
                          
                       Format component—fixed-point, four decimal places

The following code shows examples of different format strings:

   double myDouble = 12.345678;
   Console.WriteLine("{0,-10:G} -- General",                      myDouble);
   Console.WriteLine("{0,-10} -- Default, same as General",       myDouble);
   Console.WriteLine("{0,-10:F4} -- Fixed Point, 4 dec places",   myDouble);
   Console.WriteLine("{0,-10:C} -- Currency",                     myDouble);
   Console.WriteLine("{0,-10:E3} -- Sci. Notation, 3 dec places", myDouble);
   Console.WriteLine("{0,-10:x} -- Hexadecimal integer",          1194719 );

This code produces the following output:


12.345678  -- General
12.345678  -- Default, same as General
12.3457    -- Fixed Point, 4 dec places
$12.35     -- Currency
1.235E+001 -- Sci. Notation, 3 dec places
123adf     -- Hexadecimal integer

Standard Numeric Format Specifiers

Table 2-4 summarizes the nine standard numeric format specifiers. The first column lists the name of the specifier followed by the specifier characters. If the specifier characters have different output depending on their case, they are marked case-sensitive.

Image

Comments: Annotating the Code

You’ve already seen single-line comments, so here I’ll discuss the second type of inline comments—delimited comments—and mention a third type called documentation comments.

  • Delimited comments have a two-character start marker (/*) and a two-character end marker (*/).
  • Text between the matching markers is ignored by the compiler.
  • Delimited comments can span any number of lines.
   ↑ Beginning of comment spanning multiple lines
   /*
      This text is ignored by the compiler.
      Unlike single-line comments, delimited comments
      like this one can span multiple lines.
   */
    ↑ End of comment

A delimited comment can also span just part of a line. For example, the following statement shows text commented out of the middle of a line. The result is the declaration of a single variable, var2.

   Beginning of comment
       
   int /*var 1,*/ var2;
                 
          End of comment

Image Note Single-line and delimited comments behave in C# just as they do in C and C++.

More About Comments

There are a couple of other important things you need to know about comments:

  • You cannot nest delimited comments. Only one comment can be in effect at a time. If you attempt to nest comments, the comment that starts first will remain in effect until the end of its scope.
  • The scope for comment types is as follows:
    • For single-line comments, the comment will remain in effect until the end of the current line.
    • For delimited comments, the comment will remain in effect until the first end delimiter is encountered.

The following attempts at comments are incorrect:

      ↓Opens the comment
   /* This is an attempt at a nested comment.
      /*  ← Ignored because it’s inside a comment
         Inner comment
      */ ← Closes the comment because it’s the first end delimiter encountered
   */   ← Syntax error because it has no opening delimiter
   
      ↓ Opens the comment                ↓ Ignored because it’s inside a comment
   // Single-line comment   /* Nested comment?
                       */  ← Incorrect because it has no opening delimiter

Documentation Comments

C# also provides a third type of comment: the documentation comment. Documentation comments contain XML text that can be used to produce program documentation. Comments of this type look like single-line comments, except that they have three contiguous slashes rather than two. I’ll cover documentation comments in Chapter 25.

The following code shows the form of documentation comments:

   /// <summary>
   /// This class does...
   /// </summary>
   class Program
   {
      ...

Summary of Comment Types

Inline comments are sections of text that are ignored by the compiler but are included in the code to document it. Programmers insert comments into their code to explain and document it. Table 2-5 summarizes the comment types.

Image

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.186.143