Tải bản đầy đủ (.pdf) (56 trang)

Module 2: Overview of C#

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (936.19 KB, 56 trang )







Contents
Overview 1
Structure of a C# Program 2
Basic Input/Output Operations 9
Recommended Practices 15
Compiling, Running, and Debugging 22
Lab 2.1: Creating a Simple C# Program 36
Review 44

Module 2:
Overview of C#



Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual


property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

 2001−2002 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, IntelliSense, JScript, MSDN,
PowerPoint, SQL Server, Visual Basic, Visual C++, Visual C#, Visual J#, Visual Studio, and
Win32 are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.


Module 2: Overview of C# iii


Instructor Notes
This module introduces students to the C# programming language. Students
will learn about the essential elements of a basic C# program. Good
programming practices and style will also be covered. Finally, students will
learn how to use Microsoft
®
Visual Studio
®
to edit, compile, execute, and
debug a C# program.
After completing this module, students will be able to:


Explain the structure of a simple C# program.

Use the Console class of the System namespace to perform basic
input/output operations.

Handle exceptions in a C# program.

Generate Extensible Markup Language (XML) documentation for a C#
program.

Compile, link, and execute a C# program.

Use the Visual Studio Debugger to trace C# program execution.

Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need the following materials:

Microsoft PowerPoint
®
file 2124C_02.ppt

Module 2, “Overview of C#”

Lab 2, Creating a Simple C# Program

Preparation Tasks
To prepare for this module, you should:


Read all of the materials for this module.

Complete the lab.

Practice using Visual Studio .NET.

Practice the demonstrations.

Presentation:
60 Minutes

Lab:
60 Minutes
iv Module 2: Overview of C#


Demonstrations
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
Using Visual Studio to Create a C# Program
In this demonstration, you will create a C# console application by using
Visual Studio .NET.

To create a C# application
1. Start Visual Studio .NET.
2. On the File menu, point to New, and then click Project.
3. In the New Project dialog box, provide the information shown in the
following table, and then click OK.
Element Value


Project Type (tree view) Visual C# Projects
Templates (icon) Console Application
Name Hello
Location C:\temp

4. When the project has been generated, point out and discuss the following
features of Visual Studio:
• The Solution Explorer window
i. Close the Class1.cs code window.
ii. Change the name of Class1.cs to Hello.cs.
iii. Double-click Hello.cs to redisplay the code window.
• The Properties window
• The toolbars
• The View menu
• The Build menu
• The Debug menu
• The Help menu
Module 2: Overview of C# v


5. Using the code window displaying Hello.cs, point out and discuss the
following:
• The Hello namespace
Mention that namespaces will be discussed later. You could delete this
line and the corresponding braces, but leave them intact for now.
• The using directive
• The XML comments
Use this section to provide a brief description of the program. Comments
will be covered more fully later.

• The class definition
The default name for the class is Class1. Change it to Demonstrator.
• The Main method
Insert the following code:
Console.WriteLine("Hello, World");

• Microsoft IntelliSense
®

6. On the File menu, click Save All.
7. Exit Visual Studio.

Generating and Viewing XML Documentation
In this demonstration, you will show students how to compile the XML
comments that are embedded in a C# program into an XML file, and how to
view the documentation that is generated by using Microsoft Internet Explorer.

To compile XML comments and generate an XML file
1. From the Microsoft Windows
®
Start button, point to All Programs, then
click Visual Studio .NET, then click on Visual Studio .NET Tools, and
then click Visual Studio .NET Command Prompt.
2. Go to the install folder\Democode\Mod02\XML Demo folder.
3. Use WordPad to view the Hello2.cs file.
4. Discuss the XML comments in this program.
5. Return to the Command window.
6. Compile the program, and generate the XML documentation by using the
following code:
csc /doc:Hello2.xml Hello2.cs


7. At the command prompt, type the following:
Hello2.xml

Internet Explorer will start and display the XML file.
8. Exit Internet Explorer when finished.

vi Module 2: Overview of C#


Compiling and Running a C# Program
In this demonstration, you will show how to compile and run a C# program by
using Visual Studio. You will also show how to locate and correct compile-time
errors.

To compile a C# program by using Visual Studio .NET
1. Start Visual Studio .NET.
2. On the File menu, point to Open, and then click Project.
3. Open the install folder\Democode\Mod02\Converter\Converter.sln project.
4. On the Build menu, click Build Solution.
The program contains two syntax errors. Two error messages will appear in
the Task List.
5. In the Task List, double-click the first error. You will be taken to the line
containing the first error in the program (a missing “.” between Console and
ReadLine).
6. Correct the error.
7. In the Task List, double-click the second error. You will be taken to the line
containing the second error in the program (the variable degreesCelsius
spelled incorrectly as degreesCelcius).
8. Correct the error.

9. On the File menu, click Save All.
10. On the Build menu, click Build Solution.
The program will compile without errors.


To run the C# program from Visual Studio
1. On the Debug menu, click Start Without Debugging.
2. A console window containing the prompt “Please give me a temperature in
degrees F:” will appear.
3. Type the value 212 and then press ENTER.
The message “212 degrees F is 100 degrees C” will appear.
4. Press any key to close the program.

Module 2: Overview of C# vii


Using ILDASM
In this demonstration, you will show how to use Intermediate Language
Disassembler (ILDASM) to examine the manifest and Microsoft Intermediate
Language (MSIL) code in a class.

To use ILDASM to examine a class
1. From the Windows Start button, point to Programs, then click
Visual Studio .NET, then click Visual Studio .NET Tools, and then click
Visual Studio .NET Command Prompt.
2. Go to the install folder\Democode\Mod02\Converter\bin\Debug folder.
3. Type the following:
ildasm Converter.exe

ILDASM will display a window containing a tree structure.

4. Expand the Converter node.
A component named ConvertIt will appear. Point out that this is the class
that was presented in the previous demonstration.
5. Expand the ConvertIt node.
The methods, constructors, and other items that make up the class will be
displayed.
6. On the View menu, click Show source lines.
7. Double-click the Main method.
A window containing the MSIL instructions for the Main method will
appear.
a. Scroll through the window to show all of the MSIL instructions and the
C# source code.
b. Close the window.
8. Double-click MANIFEST.
A window showing the manifest (contents) of the module and its references
will appear. Close the window.
9. Close the ILDASM window.

viii Module 2: Overview of C#


Using the Visual Studio Debugger
In this demonstration, you will debug a C# program by using the Visual Studio
.NET debugger to set breakpoints and watches. You will step through code to
examine the values of variables. Please note that the demonstration Compiling
and Running a C# Program must already have been completed.
This C# program, which converts temperatures from Fahrenheit to Celsius,
contains a bug that causes incorrect temperature conversion results under some
circumstances. You will find and correct the problem.


To run the C# program
1. Open the Converter project, which is located in the
install folder\DemoCode\Mod02\Converter folder.
2. Run the program by clicking Start Without Debugging on the Debug
menu or by pressing CTRL+F5.
Explain that the program prompts the user for a temperature in degrees
Fahrenheit. It converts the user input to an integer and stores it in the
degreesFahrenheit variable. It then calculates the equivalent Celsius
temperature by using the standard conversion formula and stores the result
in the degreesCelsius variable. The program finally displays the original
Fahrenheit temperature in addition to the calculated Celsius value.
3. Type 32 at the temperature prompt.
Note for the students that the program converts this to 0 degrees Celsius,
which is correct.
4. Run the program again, and type a value of 212 at the prompt. This is the
boiling point of water.
Note for the students that the program displays the result as 100 degrees
Celsius, which is also correct.
5. Run the program a third time, and type a temperature of 75 degrees at the
prompt.
Note for the students that the result displayed is 23 degrees Celsius. This is
inaccurate because 75 degrees Fahrenheit is 23.8889 degrees Celsius.
Explain that the program seems to be truncating the result to an integer.


To identify the bug in the C# program by setting a breakpoint and by
using the Watch window
1. Set a breakpoint just after the program has read in the Fahrenheit
temperature.
2. Run the program in debug mode by clicking Start on the Debug menu or by

pressing F5.
Type 75 and press ENTER. The program reaches the breakpoint and stops.
3. Display the Watch window, and add the degreesFahrenheit and
degreesCelsius variables to the list of watched variables.
Explain that you can monitor the values of variables in the Watch window.
Module 2: Overview of C# ix


4. Run the program one line at a time from the breakpoint by clicking Step
Over on the Debug menu or by pressing F10.
This is called single-stepping. The next line of code is executed, and then
the program stops. Any changes made to the variables are shown in the
Watch window. For example, the value of degreesFahrenheit is now shown
as 75. When you step over the next line, the degreesCelsius variable is
updated with its calculated value of 23.0.
This is the line that contains the bug. The problem is that an integer
calculation is being performed on integer data before being assigned to a
floating-point variable. Rounding errors are accumulating and producing an
inaccurate result.
5. Finish program executing by pressing F5.


To fix the bug in the C# program and verifying the fix
1. Change a constant to a floating-point value by changing 32 to 32F to force
the compiler to perform a floating-point calculation.
2. Build and Run the program again.
3. Click Step Over on the Debug menu to see the results of the change.
Notice that value of degreesCelsius in the Watch window is now 23.8889.
4. Press F10 to continue stepping through the program.
5. Click Continue on the Debug menu, and the program will run until it is

finished.

x Module 2: Overview of C#


Module Strategy
Use the following strategy to present this module:

Structure of a C# Program
Describe the basic structure of a C# program. Point out that a C# application
is a collection of one or more classes, and that each class has one or more
methods. The entry point to the program is the Main method, which can
occur in any class in the application (but which should occur in only one).
Discuss how an application can use pre-written classes that were written by
other developers, and mention that the common language runtime provides a
set of numerous classes that perform a wide variety of functions. Inform
students that classes can be organized into namespaces (mention the System
namespace), and that the using directive allows the programmer to
abbreviate the full names of classes.

Basic Input/Output Operations
Explain that C# has no I/O capability of its own, but relies instead on classes
and methods in System and other namespaces. Describe the Console class,
the standard input, standard output, and standard error streams, and how
Console provides access to these streams by using the Write, WriteLine,
Read, and ReadLine methods.

Recommended Practices
Point out that good program layout and comments are important if a
program is to be maintainable. Also explain the importance of exception

handling—you never know when an exceptional circumstance could occur.
It is easier to design exception handling into a program at the start than to
try to add it later.

Compiling, Running, and Debugging
Describe and demonstrate how to compile and run a C# program from the
command line and from within Visual Studio. Explain the Just-in-Time
(JIT) compiler and options. Show how to use the Visual Studio Debugger to
debug a C# program. Finish by briefly cataloging the tools that are supplied
with the software development kit (SDK).

Module 2: Overview of C# 1


Overview

Structure of a C# Program

Basic Input/Output Operations

Recommended Practices

Compiling, Running, and Debugging

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In this module, you will learn about the basic structure of a C# program by

analyzing a simple working example. You will learn how to use the Console
class to perform some basic input and output operations. You will also learn
about some best practices for handling errors and documenting your code.
Finally, you will compile, run, and debug a C# program.
After completing this module, you will be able to:

Explain the structure of a simple C# program.

Use the Console class of the System namespace to perform basic
input/output operations.

Handle exceptions in a C# program.

Generate Extensible Markup Language (XML) documentation for a C#
program.

Compile and execute a C# program.

Use the debugger to trace program execution.

Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
about the essential
elements of C# and about
how to compile, link, and
execute a C# program.

2 Module 2: Overview of C#






Structure of a C# Program

Hello, World

The Class

The Main Method

The using Directive and the System Namespace

Demonstration: Using Visual Studio to Create
a C# Program

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In this lesson, you will learn about the basic structure of a C# program. You
will analyze a simple program that contains all of the essential features. You
will also learn how to use Microsoft
®
Visual Studio

®
to create and edit a C#
program.
Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
In this lesson, you will learn
about the basic structure of
a C# program.
Delivery Tip
In this lesson, there are
many comparisons made
between C# and other
languages that students
may be familiar with. It is
worth pointing out these
similarities and subtle (and
sometimes not-so-subtle)
differences.
Module 2: Overview of C# 3


Hello, World
using System;
class Hello
{
public static void Main()
{

Console.WriteLine("Hello, World");
}
}
using System;
class Hello
{
public static void Main()
{
Console.WriteLine("Hello, World");
}
}

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
The first program most people write when learning a new language is the
inevitable Hello, World. In this module, you will get a chance to examine the
C# version of this traditional first program.
The example code on the slide contains all of the essential elements of a C#
program, and it is easy to test! When executed from the command line, it
simply displays the following:
Hello, World

In the following topics, you will analyze this simple program to learn more
about the building blocks of a C# program.
Topic Objective
To show a complete working
C# program.

Lead-in
The first program most
people write in a new
language is the inevitable
Hello, World.
Delivery Tip
This is the style, layout, and
definition of Main that
Visual Studio uses when
creating a new C# program.

You can enter your code,
compile it, and run it from
the command line.
4 Module 2: Overview of C#


The Class

A C# application is a collection of classes, structures,
and types

A class Is a set of data and methods

Syntax

A C# application can consist of many files

A class cannot span multiple files
class name

{
...
}
class name
{
...
}

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In C#, an application is a collection of one or more classes, data structures, and
other types. In this module, a class is defined as a set of data combined with
methods (or functions) that can manipulate that data. In later modules, you will
learn more about classes and all that they offer to the C# programmer.
When you look at the code for the Hello, World application, you will see that
there is a single class called Hello. This class is introduced by using the
keyword class. Following the class name is an open brace ({). Everything up to
the corresponding closing brace (}) is part of the class.
You can spread the classes for a C# application across one or more files. You
can put multiple classes in a file, but you cannot span a single class across
multiple files.

The name of the application file does not need to be
the same as the name of the class.


C# does not distinguish between the definition and the

implementation of a class in the same way that C++ does. There is no concept
of a definition (.hpp) file. All code for the class is written in one file.

Topic Objective
To point out that every C#
application is a collection of
classes.
Lead-in
A C# application is a
collection of one or more
classes.
Delivery Tip
Do not get involved in a
thorough discussion of the
definition of a class at this
time. Keep to the simple
description in the student
notes.
Note for Java developers
Note for C++ developers
Module 2: Overview of C# 5


The Main Method

When writing Main, you should:

Use an uppercase “M”, as in “Main”

Designate one Main as the entry point to the program


Declare Main as public static void Main

Multiple classes can have a Main

When Main finishes, or returns, the application quits

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Every application must start somewhere. When a C# application is run,
execution starts at the method called Main. If you are used to programming in
C, C++, or even Java, you are already familiar with this concept.

The C# language is case sensitive. Main must be spelled with an
uppercase “M” and with the rest of the name in lowercase.

Although there can be many classes in a C# application, there can only be one
entry point. It is possible to have multiple classes each with Main in the same
application, but only one Main will be executed. You need to specify which
one should be used when the application is compiled.
The signature of Main is important too. If you use Visual Studio, it will be
created automatically as static void. (You will learn what these mean later in
the course.) Unless you have a good reason, you should not change the
signature.

You can change the signature to some extent, but it must always be static,
otherwise it might not be recognized as the application’s entry point by the

compiler.

The application runs either until the end of Main is reached or until a return
statement is executed by Main.
Topic Objective
To describe where a C#
application starts when it is
executed.
Lead-in
When a C# application runs,
execution starts with the
Main method.
Delivery Tip
When covering this topic,
stress that many of the
items discussed will be fully
explained later. The purpose
of this topic is simply to
point out the basic rules
governing the Main method.
Important
Delivery Tip
It is possible to put Main in
a struct instead of a class.
Structs will be covered in a
later module.
Tip
6 Module 2: Overview of C#



The using Directive and the System Namespace

The .NET Framework provides many utility classes

Organized into namespaces

System is the most commonly used namespace

Refer to classes by their namespace

The using directive
System.Console.WriteLine("Hello, World");
System.Console.WriteLine("Hello, World");
using System;

Console.WriteLine("Hello, World");
using System;

Console.WriteLine("Hello, World");

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
As part of the Microsoft .NET Framework, C# is supplied with many utility
classes that perform a range of useful operations. These classes are organized
into namespaces. A namespace is a set of related classes. A namespace may
also contain other namespaces.
The .NET Framework is made up of many namespaces, the most important of

which is called System. The System namespace contains the classes that most
applications use for interacting with the operating system. The most commonly
used classes handle input and output (I/O). As with many other languages, C#
has no I/O capability of its own and therefore depends on the operating system
to provide a C# compatible interface.
You can refer to objects in namespaces by prefixing them explicitly with the
identifier of the namespace. For example, the System namespace contains the
Console class, which provides several methods, including WriteLine. You can
access the WriteLine method of the Console class as follows:
System.Console.WriteLine("Hello, World");

However, using a fully qualified name to refer to objects can be unwieldy and
error prone. To ease this burden, you can specify a namespace by placing a
using directive at the beginning of your application before the first class is
defined. A using directive specifies a namespace that will be examined if a
class is not explicitly defined in the application. You can put more than one
using directive in the source file, but they must all be placed at the beginning of
the file.
Topic Objective
To describe the purpose of
the using directive for
accessing namespaces.
Lead-in
C# is supplied with many
utility classes that are
organized into namespaces.
Delivery Tip
Namespaces are covered in
detail in Module 11,
“Aggregation, Namespaces

and Advanced Scope,” in
Course 2124C,
Programming with C#. The
information provided here is
sufficient to understand the
using directive.
Module 2: Overview of C# 7


With the using directive, you can rewrite the previous code as follows:
using System;
...
Console.WriteLine("Hello, World");

In the Hello, World application, the Console class is not explicitly defined.
When the Hello, World application is compiled, the compiler searches for
Console and finds it in the System namespace instead. The compiler generates
code that refers to the fully qualified name System.Console.

The classes of the System namespace, and the other core functions
accessed at run time, reside in an assembly called mscorlib.dll. This assembly is
used by default. You can refer to classes in other assemblies, but you will need
to specify the locations and names of those assemblies when the application is
compiled.

Delivery Tip
Make sure C and C++
programmers understand
the difference between the
using directive and the

#include statement. Java
developers will be more
familiar with this feature, as
it is similar to the import
directive.
Note
8 Module 2: Overview of C#


Demonstration: Using Visual Studio to Create a C# Program

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In this demonstration, you will learn how to use Visual Studio to create and edit
C# programs.
Topic Objective
To demonstrate how to use
Visual Studio to create and
edit a C# program.
Lead-in
In Visual Studio, you can
edit and compile C# code
just as you can with other
more familiar languages like
C++ and Microsoft
Visual Basic
®

.
Delivery Tip
The step-by-step
instructions for this
demonstration are in the
instructor notes for this
module.
Module 2: Overview of C# 9






Basic Input/Output Operations

The Console Class

Write and WriteLine Methods

Read and ReadLine Methods

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In this lesson, you will learn how to perform command-based input/output
operations in C# by using the Console class. You will learn how to display
information by using the Write and WriteLine methods, and how to gather

input information from the keyboard by using the Read and ReadLine
methods.
Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
In this lesson, you will learn
how to perform basic
console-oriented I/O
operations in C#.
10 Module 2: Overview of C#


The Console Class

Provides access to the standard input, standard output,
and standard error streams

Only meaningful for console applications

Standard input – keyboard

Standard output – screen

Standard error – screen

All streams may be redirected

*****************************

ILLEGAL FOR NON
-
TRAINER USE
******************************
The Console class provides a C# application with access to the standard input,
standard output, and standard error streams.
Standard input is normally associated with the keyboard—anything that the user
types on the keyboard can be read from the standard input stream. Similarly, the
standard output stream is usually directed to the screen, as is the standard error
stream.

These streams and the Console class are only meaningful to console
applications. These are applications that run in a Command window.

You can direct any of the three streams (standard input, standard output,
standard error) to a file or device. You can do this programmatically, or the user
can do this when running the application.
Topic Objective
To describe the purpose of
the Console class.
Lead-in
You can use methods of the
Console class to read input
from the keyboard or to
write output to the screen.
Delivery Tip
Emphasize that the
Console class should only
be used for command-line
applications. Developers

writing graphical user
interface (GUI) applications
should use classes in the
System.Windows.Forms
namespace.
Note
Module 2: Overview of C# 11


Write and WriteLine Methods

Console.Write and Console.WriteLine display
information on the console screen

WriteLine outputs a line feed/carriage return

Both methods are overloaded

A format string and parameters can be used

Text formatting

Numeric formatting

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
You can use the Console.Write and Console.WriteLine methods to display

information on the console screen. These two methods are very similar; the
main difference is that WriteLine appends a new line/carriage return pair to the
end of the output, and Write does not.
Both methods are overloaded. You can call them with variable numbers and
types of parameters. For example, you can use the following code to write “99”
to the screen:
Console.WriteLine(99);

You can use the following code to write the message “Hello, World” to the
screen:
Console.WriteLine("Hello, World");

Text Formatting
You can use more powerful forms of Write and WriteLine that take a format
string and additional parameters. The format string specifies how the data is
output, and it can contain markers, which are replaced in order by the
parameters that follow. For example, you can use the following code to display
the message “The sum of 100 and 130 is 230”:
Console.WriteLine("The sum of {0} and {1} is {2}", 100, 130,
100+130);


The first parameter that follows the format string is referred to as
parameter zero: {0}.

Topic Objective
To describe the Write and
WriteLine methods of the
Console class.
Lead-in

The Write and WriteLine
methods provide a means of
sending information to the
standard output stream.
Delivery Tip
You may want to draw
parallels with cout in C++,
printf in C, and
System.out.print in Java,
depending upon the
audience. There is really no
equivalent function in
Visual Basic.

Also, keep any discussion
about method overloading
brief and simple. Some
students may not yet
understand it, and it is
covered more fully in a later
module.
Important
12 Module 2: Overview of C#


You can use the format string parameter to specify field widths and whether
values should be left or right justified in these fields, as shown in the following
code:
Console.WriteLine("\"Left justified in a field of width 10:
{0, -10}\"", 99);

Console.WriteLine("\"Right justified in a field of width 10:
{0,10}\"", 99);

This will display the following on the console:
“Left justified in a field of width 10: 99 ”
“Right justified in a field of width 10: 99”

You can use the backward slash (\) character in a format string to turn off
the special meaning of the character that follows it. For example, "\{" will cause
a literal "{" to be displayed, and "\\" will display a literal "\". You can use the at
sign (@) character to represent an entire string verbatim. For example,
@"\\server\share" will be processed as "\\server\share."

Numeric Formatting
You can also use the format string to specify how numeric data is to be
formatted. The full syntax for the format string is
{N,M:FormatString}
,
where
N
is the parameter number,
M
is the field width and justification, and
FormatString
specifies how numeric data should be displayed. The table
below summarizes the items that may appear in FormatString. In all of these
formats, the number of digits to be displayed, or rounded to, can optionally be
specified.
Item Meaning


C Display the number as currency, using the local currency symbol and
conventions.
D Display the number as a decimal integer.
E Display the number by using exponential (scientific) notation.
F Display the number as a fixed-point value.
G Display the number as either fixed point or integer, depending on which
format is the most compact.
N Display the number with embedded commas.
X Display the number by using hexadecimal notation.

Note
Module 2: Overview of C# 13


The following code shows some examples of how to use numeric formatting:
Console.WriteLine("Currency formatting - {0:C} {1:C4}", 88.8,
-888.8);
Console.WriteLine("Integer formatting - {0:D5}", 88);
Console.WriteLine("Exponential formatting - {0:E}", 888.8);
Console.WriteLine("Fixed-point formatting - {0:F3}",
888.8888);
Console.WriteLine("General formatting - {0:G}", 888.8888);
Console.WriteLine("Number formatting - {0:N}", 8888888.8);
Console.WriteLine("Hexadecimal formatting - {0:X4}", 88);

When the previous code is run, it displays the following:
Currency formatting - $88.80 ($888.8000)
Integer formatting - 00088
Exponential formatting - 8.888000E+002
Fixed-point formatting - 888.889

General formatting - 888.8888
Number formatting - 8,888,888.80
Hexadecimal formatting – 0058


For more information on formatting, search “formatting strings” in
Microsoft MSDN
®
Help.

Note
14 Module 2: Overview of C#


Read and ReadLine Methods

Console.Read and Console.ReadLine read user input

Read reads the next character

ReadLine reads the entire input line

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
You can obtain user input from the keyboard by using the Console.Read and
Console.ReadLine methods.
The Read Method

Read reads the next character from the keyboard. It returns the int value –1 if
there is no more input available. Otherwise it returns an int representing the
character read.
The ReadLine Method
ReadLine reads all characters up to the end of the input line (the carriage return
character). The input is returned as a string of characters. You can use the
following code to read a line of text from the keyboard and display it to the
screen:
string input = Console.ReadLine( );
Console.WriteLine("{0}", input);

Topic Objective
To describe the Read and
ReadLine methods of the
Console class.
Lead-in
You can use the Read and
ReadLine methods to get
user input from the
keyboard.
Delivery Tip
There is deliberately no
example given of Read.
This is because, for the
example to have any
meaning, it would need to
show how to cast from an
integer (returned by Read)
to a character:


int i;
char c;
i = Console.Read( );
c = (char) i;
Console.WriteLine(c);
Module 2: Overview of C# 15






Recommended Practices

Commenting Applications

Generating XML Documentation

Demonstration: Generating and Viewing XML
Documentation

Exception Handling

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In this lesson, you will learn some recommended practices to use when writing
C# applications. You will be shown how to comment applications to aid

readability and maintainability. You will also learn how to handle the errors
that can occur when an application is run.
Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
In this lesson, you will learn
some recommended
practices to use when
writing C# applications.

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

Tải bản đầy đủ ngay
×