Chapter 2. Overview of C# Programming

A Simple C# Program

This chapter will lay the groundwork for studying C#. Since I will 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 under your belt, I can then use code samples freely throughout the rest of the text. So, unlike the following chapters, where one or two topics will be covered in detail, this chapter will touch on many topics with only a minimum of explanation.

Let's start by looking at a simple C# program. The complete program source is shown in the top shaded area in 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.

  • When the code is compiled and executed, it displays the string "Hi there!" in a window on the screen.

  • One line 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.

The SimpleProgram program

Figure 2-1. The SimpleProgram program

Table 2-1. The SimpleProgram Program, Line by Line

Line Number

Description

Line 1

Tells the compiler that this program uses types from the System namespace.

Line 3

Declares a new namespace, called Simple.

  • The new namespace starts at the open curly brace on line 4 and extends through the matching curly brace on line 12.

  • Any types declared within this section are members of the namespace.

Line 5

Declares a new class type, called Program.

  • Any members declared between the matching curly braces on lines 6 and 11 are members that make up this class.

Line 7

Declares a method called Main as a member of class Program.

  • In this program, Main is the only member of the Program class.

  • Main is a special function used by the compiler as the starting point of the program.

Line 9

Contains only a single, simple statement; this line constitutes the body of Main.

  • Simple statements are terminated by a semicolon.

  • This statement uses a class called Console, in namespace System, to print out the message to a window on the screen.

  • Without the using statement inline 1, the compiler wouldn't have known where to look for class Console.

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 the class type is declared.

A namespace is aset of type declarations associated with a name. SimpleProgram uses two namespaces. It creates a new namespace called Simple, and uses a predefined 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:

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.

Identifiers and Keywords

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, SocSecurityNum). Certain characters are allowed or disallowed at certain positions in an identifier. These rules are illustrated in Figure 2-2.

  • 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 anywhere else. The use of the @ character, although allowed, is discouraged for general use.

Characters allowed in identifiers

Figure 2-2. Characters allowed in identifiers

Identifiers are case sensitive. For instance, the variable names myVar and MyVar are different identifiers. It is generally a bad idea, however, to have identifiers that differ only in the case of some of the letters.

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 don't do this!
int totalCycleCount;
int TotalCycleCount;
int TotalcycleCount;

Naming Conventions

The C# Language Specification suggests that certain casing conventions be used in creating identifiers. The suggested guidelines for casing are described and summarized in Table 2-2.

For most identifiers, the Pascal casing style should be used. In this style, each of the words combined to make an identifier is capitalized—for example, FirstName and LastName.

Table 2-2. Recommended Identifier Naming Styles

Style Name

Description

Recommended Use

Examples

Pascal casing

Each word in the identifier is capitalized.

Use for type names and member names.

CardDeck, DealersHand

Camel casing

Each word in the identifier, except the first, is capitalized.

Use for local variables and method parameters.

totalCycleCount, randomSeedParam

Uppercase

The identifier is composed of all uppercase letters.

Use only for abbreviations.

IO, DMA, XML

Although these are the suggested guidelines, many organizations use other conventions—particularly in the naming of member fields, which will be introduced in the next chapter. Two of the common conventions are the following:

  • Begin a field name with an underscore: _HighTemp, _LowTemp.

  • Begin a field name with m_: m_HighTemp, m_LowTemp.

Both of these methods have the advantage of showing you immediately that these identifiers are field names. These forms also allow Visual Studio's IntelliSense feature to group all the fields together in the pop-ups.

Keywords

Keywords are the character string tokens used to define the C# language. A complete list of the C# keywords is given in Table 2-3.

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.

Table 2-3. The C# Keywords

abstract

const

extern

int

out

short

typeof

as

continue

false

interface

override

sizeof

uint

base

decimal

finally

internal

params

stackalloc

ulong

bool

default

fixed

is

private

static

unchecked

break

delegate

float

lock

protected

string

unsafe

byte

do

for

long

public

struct

ushort

case

double

foreach

namespace

readonly

switch

using

catch

else

goto

new

ref

this

virtual

char

enum

if

null

return

throw

void

checked

event

implicit

object

sbyte

true

volatile

class

explicit

in

operator

sealed

try

while

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. The list of contextual keywords is shown in Table 2-4.

Table 2-4. The C# Contextual Keywords

ascending

by

descending

equals

from

get

group

into

join

let

on

orderby

partial

select

set

value

where

yield

   

Main: The Starting Point of a Program

Every C# program must have one class with a method (function) 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 will introduce the general form of statements; the specific statement forms will be covered in Chapter 9.

Simple Statements

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 a 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—but it's not good style.)

Blocks

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.

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

Write

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 the string, so the output of the three statements runs together on a single line.

Write

WriteLine

WriteLine is another member of Console, which 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 text 1.");
System.Console.WriteLine("This is text 2.");
System.Console.WriteLine("This is text 3.");

This code produces the following output in the console window:

This is text 1.
This is text 2.
This is text 3.

The Format String

The general form of the Write and WriteLine statements takes 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. It 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.

The Format String

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. Notic8e 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 displays the following on the screen:

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.

Multiple Markers and Values

Comments: Annotating the Code

You have 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 start marker and an end marker.

  • Text between the matching markers is ignored by the compiler.

  • Delimited comments can span any number of lines.

For example, the following code shows a delimited comment spanning multiple lines.

Comments: Annotating the Code

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.

Comments: Annotating the Code

Note

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

More About Comments

There are several other important things you need to know about comments:

  • Nested comments are not allowed. Only one comment can be in effect at a time.

  • The comment that starts first is in effect until the end of its scope. The scope for particularly comment types is as follows:

    • For single-line comments, the end of the current line

    • For delimited comments, the first end delimiter encountered

The following attempts at comments are incorrect:

More About Comments

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 will 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 gives a summary of the comment types.

Table 2-5. Comment Types

Type

Start

End

Description

Single-line

//

 

The text from the beginning marker to the end of the current line is ignored by the compiler.

Delimited

/*

*/

The text between the start and end markers is ignored by the compiler.

Documentation

///

 

Comments of this type contain XML text that is meant to be used by a tool to produce program documentation.

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

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