Tải bản đầy đủ - 0 (trang)
Chapter 3. C# Overview for Sophisticated Programmers

Chapter 3. C# Overview for Sophisticated Programmers

Tải bản đầy đủ - 0trang

Hello World in C#

Whenever learning a new programming language, a good first step is to write and

run a simple program that will display a single line of text. Such a program

demonstrates the basic structure of the language, including output.

Here is "Hello, World" in C#. (See the Hello directory for this chapter.)

// Hello.cs

using System;

class Hello


public static int Main(string[] args)


Console.WriteLine("Hello, World");

return 0;



Compiling and Running (Command Line)

You can learn how to use the Microsoft Visual Studio.NET IDE (integrated

development environment) in Appendix A. You can also use the command-line

tools of the .NET Framework SDK. Be sure to get the environment variables set

up properly, as described in the sidebar. To compile this program at the command

line, enter the command

>csc Hello.cs

An executable file Hello.exe will be generated. To execute your program, type at

the command line:


The program will now execute, and you should see displayed the greeting:

Hello, World

Setting Environment Variables

In order to run command-line tools such as the C# compiler using a

simple name such as csc rather than a complete path, we must set certain

environment variables. To do so we can use a batch file, corvars.bat,

which can be found in the bin directory of the Framework SDK.

I experienced different behavior in different beta versions of the .NET

Framework SDK. In one version the environment variables were set up

automatically as part of the install, and in another version I had to use

the corvars.bat file.

If you have Visual Studio.NET installed, you can ensure that the

environment variables are set up by starting your command prompt

session from Start | Programs | Microsoft Visual Studio.NET 7.0 |

Microsoft Visual Studio Tools | Microsoft Visual Studio.NET

Command Prompt.

Program Structure

// Hello.cs

class Hello




Every C# program has at least one class. A class is the foundation of C#'s support

of object-oriented programming. A class encapsulates data (represented by

variables) and behavior (represented by methods). All of the code defining the

class (its variables and methods) will be contained between the curly braces. We

will discuss classes in detail later.

Note the comment at the beginning of the program. A line beginning with a

double slash is present only for documentation purposes and is ignored by the

compiler. C# files have the extension .cs.

// Hello.cs


An alternate form of comment is to use an opening /* and a closing */.

/* This is a comment

that may be continued over

several lines */

There is a distinguished class, which has a method whose name must be Main.

The method should be public and static. An int exit code can be returned to the

operating system. Note that in C# the file name need not be the same as the name

of the class containing the Main method.

// Hello.cs

using System;

class Hello


public static int Main(string[] args)



return 0;



Use void if you do not return an exit code.

public static void Main(string[] args)

Command-line arguments are passed as an array of strings. The runtime will call

this Main method—it is the entry point for the program. All the code of the Main

method will be between the curly braces.

// Hello.cs

using System;

class Hello


public static int Main(string[] args)


Console.WriteLine("Hello, World");

return 0;



Every method in C# has one or more statements. A statement is terminated by a

semicolon. A statement may be spread out over several lines.

The Console class provides support for standard output and standard input. The

method WriteLine displays a string, followed by a new line.


Much standard functionality in C# is provided through many classes in the .NET

Framework. Related classes are grouped into namespaces. Many useful classes,

such as Console, are in the System namespace. The fully qualified name of a

class is specified by the namespace followed by a dot followed by a class name.


A using statement allows a class to be referred to by its class name alone.

// Hello.cs

using System;

class Hello


public static int Main(string[] args)


Console.WriteLine("Hello, World");

return 0;



Performing Calculations in C#

Our "Hello, World" program illustrated the basic structure of a C# program, but we will need a

slightly more elaborate example to show the use of other basic programming constructs, such as

variables, expressions, and control structures. Our next example is a simple calculator for an IRA

account. We calculate the accumulation of deposits to an IRA of $2000.00 a year at 6% interest for

10 years, assuming that each deposit is made at the end of the year. Our calculation is performed

two ways:

In a loop, year by year, accumulating a total as we go

Using a formula

The example program is in the folder Ira\Step1.

// Ira.cs - Step 1

using System;

class Ira


public static int Main(string[] args)


int years = 10;

decimal rate = 0.06m;

decimal amount = 2000M;

decimal interest;

decimal total = 0m;

Console.WriteLine("{0,4} {1,12} {2,12} {3,12}",

"Year", "Amount", "Interest", "Total");

for (int i = 1; i <= years; i++)


interest = total * rate;

total += amount + interest;


"{0, -4} {1, 12:C} {2, 12:C} {3, 12:C}",

i, amount, interest, total);


Console.WriteLine("\nTotal using formula = {0}",

IraTotal(years, (double) rate, (double) amount));

return 0;


public static double IraTotal(int years, double rate,

double amount)


double total =

amount * (Math.Pow(1 + rate, years) - 1) / rate;

long total_in_cents = (long) Math.Round(total * 100);

total = total_in_cents /100.0;

return total;



If you compile and run it, you will see this output:













































Total using formula = 26361.59


In C# variables are of a specific data type. Some common types are int for integers and double for

floating-point numbers. C# has the decimal data type, which has a high degree of precision,

suitable for monetary calculations.

You must declare and initialize variables before you can use them.

int years = 10;

decimal interest;





reserves space and assigns

an initial value

reserves space but does

not initialize it to any value

If an initial value is not specified in the declaration, the variable must be initialized in code before

it can be used. We will discuss initialization later in the chapter.

Variables must be either local within a method or members of a class. There are no global variables

in C#.


A literal is used when you explicitly write a value for a variable in a program. An integer literal is

represented by either an ordinary decimal integer or a hexadecimal integer. A floating-point or

decimal literal is represented by a number with a decimal point or by exponential notation. You

may influence the type [1] that is used for storing a literal by a suffix. The suffix f or F indicates

single precision floating point. The suffix d or D indicates double precision floating point. The

suffix m or M indicates decimal (think money).


We discuss C# types, such as float, double, and decimal, later in the chapter.

decimal rate = 0.06m;

decimal amount = 2000M;

There are two forms for string literals. Escape sequences are not processed for string literals that

are prefixed with @.

string file1 ="c:\\test1.txt";

string file2 = @"c:\test2.txt";

C# Operators and Expressions

You can combine variables and literals via operators to form expressions. The C# operators are

similar to those in C and C++, having similar precedence and associativity rules. There are three

kinds of operators,

Unary operators take one operand and use prefix notation (e.g., --a) or postfix notation (e.g.,


Binary operators take two operands and use infix notation (e.g., a + b).

The one ternary operator ?: takes three operands and uses infix notation (e.g., expr ? x : y).

Operators are applied in the precedence order shown in Table 3-1. For operators of the same

precedence, order is determined by associativity.

The assignment operator is right-associative (operations are performed from right to left).

All other binary operators are left-associative (operations are performed from left to right).

Precedence and associativity can be controlled by parentheses; what is done first is shown as the

primary operator (x) in the precedence table. C# has checked and unchecked operators, which will

be discussed later.

Table 3-1. Operator Precedence in C#




(x) x.y f(x) a[x] x++ x- new typeof sizeof

checked unchecked


+ - ! ~ ++x --x (T)x

Multiplicative * / %


+ -


<< >>


< > <= >= is as


== !=

Logical AND


Logical XOR


Logical OR


Conditional AND &&

Conditional OR ||




= *= /= %= += -= <<= >>= &= ^= |=

Output and Formatting

The Console class in the System namespace supports two simple methods for performing output:

WriteLine writes out a string followed by a new line.

Write writes out just the string without the new line.

You can write out other data types by relying on the ToString method of System.Object, which

will provide a string representation of any data type. We will discuss the root class System.Object

in Chapter 5, where you will also see how to override ToString for your own custom data type.

You can use the string concatenation operator + to build up an output string.

int x = 24;

int y = 5;

int z = x * y;

Console.Write("Product of " + x + " and " + y);

Console.WriteLine(" is " + z);

The output is all on one line:

Product of 24 and 5 is 120


A more convenient way to build up an output string is to use placeholders {0}, {1}, and so on. An

equivalent way to do the output shown above is

Console.WriteLine("Product of {0} and {1} is {2}", x,y,z);

The program OutputDemo illustrates the output operations just discussed.

We will generally use placeholders for our output from now on. Placeholders can be combined

with formatting characters to control output format.

Format Strings

C# has extensive formatting capabilities, which you can control through placeholders and format


Simple placeholders: {n}, where n is 0, 1, 2, . . . , indicating which variable to insert

Control width: {n,w}, where w is width (positive for right-justified and negative for leftjustified) of the inserted variable

Format string: {n:S}, where S is a format string indicating how to display the variable

Width and format string: {n,w:S}

A format string consists of a format character followed by an optional precision specifier. Table 32 shows the available format characters.

Table 3-2. C# Format Characters

Format Character



Currency (locale specific)


Decimal integer


Exponential (scientific)


Fixed point


General (E or F)


Number with embedded commas



Sample Formatting Code

The program FormatDemo illustrates formatting. Our sample program Ira\Step1 provides another

example. The header uses width specifiers, and the output inside the loop uses width specifiers and

the currency format character.


Console.WriteLine("{0,4} {1,12} {2,12} {3,12}",

"Year", "Amount", "Interest", "Total");

for (int i = 1; i <= years; i++)


interest = total * rate;

total += amount + interest;


"{0, -4} {1, 12:C} {2, 12:C} {3, 12:C}",

i, amount, interest, total);



Control Structures

The preceding code fragment illustrates a for loop. The C# control structures include the familiar

control structures of the C family of languages,










These all have standard semantics, except for switch, which is less error-prone in C#. There are

several other control statements in C#:

There is a foreach loop, which we will discuss later in connection with arrays and


The throw statement is used with exceptions. We will discuss exceptions later in this


The lock statement can be used to enforce synchronization in multithreading situations. We

will discuss multithreading in Chapter 8.

Switch Statement

In C#, after a particular case statement is executed, control does not automatically continue to the

next statement. You must explicitly specify the next statement, typically by a break or goto label.

(As in C and C++, you may call for identical handling of several cases by having empty statements

for all the case labels except the last one.) In C# you may also switch on a string data type. The

program SwitchDemo illustrates use of the switch statement in C#.




case 1:

Console.Write("Very ");

goto case 2;

// cannot fall through

case 2:



case 3:



case 4:

case 5:




Console.WriteLine("Special Case");





Our Ira\Step1 example program has a method IraTotal for computing the total IRA accumulation

by use of a formula. In C# every function is a method of some class; there are no freestanding

functions. If the method does not refer to any instance variables of the class, the method can be

static. We will discuss instance data of a class later in this chapter. Since the method is accessed

only from within the class, it is designated as private.

Note the use of the Pow and Round methods of the Math class, which is another class in the

System namespace. These methods are static methods. To call a static method from outside the

class in which it is defined, place the name of the class followed by a period before the method

name. In C# you cannot employ the alternative C++ style of using an instance name to qualify a

static method.


private static double IraTotal(int years, double rate,

double amount)


double total =

amount * (Math.Pow(1 + rate, years) - 1) / rate;

long total_in_cents = (long) Math.Round(total * 100);

total = total_in_cents /100.0;

return total;



Console Input in C#

Our first Ira program is not too useful, because the data are hardcoded. To perform the calculation

for different data, you would have to edit the source file and recompile. What we really want to do

is allow the user of the program to enter the data at runtime.

An easy, uniform way to do input for various data types is to read the data as a string and then

convert to the desired data type. Use the ReadLine method of the System.Console class to read in

a string. Use the ToXxxx methods of the System.Convert class to convert the data to the type you


Console.Write("amount: ");

string data = Console.ReadLine();

amount = Convert.ToDecimal(data);

Although console input in C# is fairly simple, we can make it even easier using object-oriented

programming. We can encapsulate the details of input in an easy-to-use wrapper class,

InputWrapper (which is not part of the .NET Framework class library).

Using the InputWrapper Class

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 3. C# Overview for Sophisticated Programmers

Tải bản đầy đủ ngay(0 tr)