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

Module 3: Using Value- Type Variables

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 (860.12 KB, 38 trang )







Contents
Overview 1
Common Type System 2
Naming Variables 8
Using Built-in Data Types 14
Creating User-Defined Data Types 22
Converting Data Types 26
Lab 3.1: Creating and Using Types 30
Review 34

Module 3: Using Value-
Type Variables


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 3: Using Value-Type Variables iii

Instructor Notes
This module provides students with an overview of the Common Type System
(CTS). Students will learn about value-type variables. They will also create and
use user-defined data types.
After completing this module, students will be able to:

Describe the types of variables that can be used in C# applications.

Name variables according to standard C# naming conventions.

Declare variables by using built-in data types.

Assign values to variables.


Convert existing variables from one data type to another.

Create and use their own data types.

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_03.ppt

Module 3, “Using Value-Type Variables”

Lab 3, Creating and Using Types

Preparation Tasks
To prepare for this module, you should:

Read all of the materials for this module.

Complete the lab.

Read the instructor notes and the margin notes for the module.


Read the Naming Guidelines located in the Microsoft .NET Framework
Software Development Kit (SDK) Help documents.

Read the Technical Overview of the Common Language Runtime located in
the .NET Framework SDK Help documents.

Presentation:
60 Minutes

Lab:
35 Minutes
iv Module 3: Using Value-Type Variables

Module Strategy
Use the following strategy to present this module:

Common Type System
Start this discussion by reminding students that the CTS is a part of the
common language runtime (which is covered in Module 1, “Overview of the
Microsoft .NET Platform,” in Course 2124C, Programming with C#. Then
discuss the two different categories of types available to programmers in the
.NET Framework.

Naming Variables
Start this discussion by reminding students that they must follow the rules
and recommendations for C# naming conventions to develop code that
functions and is consistent. Discuss the naming rules and recommendations
for choosing identifiers and reserved keywords.

Using Built-in Data Types

Explain how to declare local variables and how to handle initially
unassigned variables. Discuss the assignment operators (=, +=, and so on).
Explain compound assignment, increment, and decrement. Explain the
implicit and explicit conversion. Discuss common operators such as
equality, relational, conditional, and logical operators. Also explain operator
precedence and associativity.

Creating User-Defined Data Types
Explain how to use enum and struct data types and the advantage of the
struct data type.

Converting Data Types
Explain implicit and explicit data type conversions.

Module 3: Using Value-Type Variables 1

Overview

Common Type System

Naming Variables

Using Built-in Data Types

Creating User-Defined Data Types

Converting Data Types

*****************************
ILLEGAL FOR NON

-
TRAINER USE
******************************
All applications manipulate data in some way. As a C# developer, you need to
understand how to store and process data in your applications. Whenever your
application needs to store data temporarily for use during execution, you store
that data in a variable. Before you use a variable, you must define it. When you
define a variable, you reserve some storage for that variable by identifying its
data type and giving it a name. After a variable is defined, you can assign
values to that variable.
In this module, you will learn how to use value-type variables in C#. You will
learn how to specify the type of data that variables will hold, how to name
variables according to standard naming conventions, and how to assign values
to variables. You also will learn how to convert existing variables from one data
type to another and how to create your own variables.
After completing this module, you will be able to:

Describe the types of variables that you can use in C# applications.

Name your variables according to standard C# naming conventions.

Declare a variable by using built-in data types.

Assign values to variables.

Convert existing variables from one data type to another.

Create and use your own data types.

Topic Objective

To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
how to use value-type
variables in C#.
Delivery Tip
For more information about
topics mentioned in this
module, see the .NET
Framework class library
documentation and the C#
Language Specification in
the Visual Studio .NET Help
documents.
2 Module 3: Using Value-Type Variables





Common Type System

Overview of CTS

Comparing Value and Reference Types

Comparing Built-in and User-Defined Value Types


Simple Types

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Every variable has a data type that determines what values can be stored in the
variable. C# is a type-safe language, meaning that the C# compiler guarantees
that values stored in variables are always of the appropriate type.
The common language runtime includes a Common Type System (CTS) that
defines a set of built-in data types that you can use to define your variables.
After completing this lesson, you will be able to:

Describe how the CTS works.

Choose the appropriate data types for your variables.

Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
In this section, you will learn
about some of the data
types in C#. You will also
learn about the Common
Type System.
Module 3: Using Value-Type Variables 3


Overview of CTS

CTS supports both value and reference types
Reference Type
Reference Type
Type
Type
Value Type
Value Type

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
When you define a variable, you need to choose the right data type for your
variable. The data type determines the allowable values for that variable, which,
in turn, determine the operations that can be performed on that variable.
CTS
CTS is an integral part of the common language runtime. The compilers, tools,
and the runtime itself share CTS. It is the model that defines the rules that the
runtime follows when declaring, using, and managing types. CTS establishes a
framework that enables cross-language integration, type safety, and high-
performance code execution.
In this module, you will learn about two types of variables:

Value-type variables.

Reference-type variables.


Topic Objective
To describe CTS.
Lead-in
CTS supports procedural
and object-oriented
programming styles. The
CTS also supports value
and reference types.
4 Module 3: Using Value-Type Variables

Comparing Value and Reference Types

Value types:

Directly contain their
data

Each has its own
copy of data

Operations on one
cannot affect another

Reference types:

Store references to their
data (known as objects)

Two reference variables
can reference same object


Operations on one can
affect another

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Value Types
Value-type variables directly contain their data. Each value-type variable has its
own copy of the data, so it is not possible for operations on one variable to
affect another variable.
Reference Types
Reference-type variables contain references to their data. The data for
reference-type variables is stored in an object. It is possible for two reference-
type variables to reference the same object, so it is possible for operations on
one reference variable to affect the object referenced by another reference
variable.

All of the base data types are defined in the System namespace. All types
are ultimately derived from System.Object. Value types are derived from
System.ValueType.

For more information about reference types, see Module 8, “Using Reference-
Type Variables,” in Course 2124C, Programming with C#.
Topic Objective
To describe differences
between value and
reference types.

Lead-in
The focus of this module is
on value types. Value types
and reference types have
significant differences that
developers need to
understand.
Note
Module 3: Using Value-Type Variables 5

Comparing Built-in and User-Defined Value Types

Examples of
built-in value types:

int

float

Examples of user-defined
value types:

enum

struct
User-Defined
User-Defined
Value Types
Value Types
Built-in Type

Built-in Type

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Value types include built-in and user-defined data types. The difference
between built-in and user-defined types in C# is minimal because user-defined
types can be used in the same way as built-in ones. The only real difference
between built-in data types and user-defined data types is that you can write
literal values for the built-in types. All value types directly contain data, and
they cannot be null.
You will learn how to create user-defined data types such as enumeration and
structure types in this module.
Topic Objective
To compare built-in and
user-defined value types.
Lead-in
Value types include built-in
and user-defined types. In
this topic you will look at
some examples of each
type.
6 Module 3: Using Value-Type Variables

Simple Types

Identified through reserved keywords


int // Reserved keyword
-or -

System.Int32

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Built-in value types are also referred to as basic data types or simple types.
Simple types are identified by means of reserved keywords. These reserved
keywords are aliases for predefined struct types.
A simple type and the struct type it aliases are completely indistinguishable. In
your code, you can use the reserved keyword or you can use the struct type. The
following examples show both:
byte // Reserved keyword

–Or–
System.Byte // struct type


int // Reserved keyword

–Or–
System.Int32 // struct type

For more information about the sizes and ranges of built-in value types, search
for “Value Types” in the Microsoft
®

Visual Studio
®
.NET Help documents.
Topic Objective
To describe simple types.
Lead-in
C# provides a set of
predefined struct types
called simple types.
Module 3: Using Value-Type Variables 7

The following table lists common reserved keywords and their equivalent
aliased struct type.
Reserved keywords Alias for struct type

sbyte System.SByte
byte System.Byte
short System.Int16
ushort System.UInt16
int System.Int32
uint System.UInt32
long System.Int64
ulong System.UInt64
char System.Char
float System.Single
double System.Double
bool System.Boolean
decimal System.Decimal

8 Module 3: Using Value-Type Variables






Naming Variables

Rules and Recommendations for Naming Variables

C# Keywords

Quiz: Can You Spot Disallowed Variable Names?

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
To use a variable, you first choose a meaningful and appropriate name for the
variable. Each variable has a name that is also referred to as the variable
identifier.
When naming variables, follow the standard naming conventions recommended
for C#. You also need to be aware of the C# reserved keywords that you cannot
use for variable names.
After completing this lesson, you will be able to:

Identify C# standard reserved keywords.

Name your variables according to standard C# naming conventions.


Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
In this section, you will learn
how to assign and use
meaningful variable names
in a C# application.
Module 3: Using Value-Type Variables 9

Rules and Recommendations for Naming Variables

Rules

Use letters, the underscore,
and digits

Recommendations

Avoid using all
uppercase letters

Avoid starting with
an underscore

Avoid using abbreviations

Use PascalCasing naming
in multiple-word names

different
Different
different
Different
Answer42
42Answer
Answer42
42Answer








BADSTYLE
_poorstyle
BestStyle
BADSTYLE
_poorstyle
BestStyle






Msg
Message

Msg
Message





*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
When you name variables, observe the following rules and recommendations.
Rules
The following are the naming rules for C# variables:

Start each variable name with a letter or underscore character.

After the first character, use letters, digits, or the underscore character.

Do not use reserved keywords.

If you use a disallowed variable name, you will get a compile-time error.

Recommendations
It is recommended that you follow these recommendations when naming your
variables:

Avoid using all uppercase letters.


Avoid starting with an underscore.

Avoid using abbreviations.

Use PascalCasing naming in multiple-word names.

Topic Objective
To learn the rules for
naming variables.
Lead-in
There are rules and
recommendations that you
must follow when choosing
a variable name.
Delivery Tip
Point out that C# is case
sensitive, like C and C++.
Delivery Tip
Encourage students to
follow these
recommendations. Point out
that using standard naming
conventions will help them
to develop code that is
consistent and easy to
maintain.
10 Module 3: Using Value-Type Variables

PascalCasing Naming Convention
To use the PascalCasing naming convention, capitalize the first character of

each word. Use PascalCasing for classes, methods, properties, enums,
interfaces, read only and constant fields, namespaces, and properties, as shown
in the following example:
void InitializeData( );

camelCasing Naming Convention
To use the camelCasing naming convention, capitalize the first character of
each word except for the first word. Use camelCasing for variables that define
fields and parameters, as shown in the following example:
int loopCountMax;

For more information about naming conventions, see “Naming Guidelines” in
the .NET Framework Software Development Kit (SDK) Help documents.
Module 3: Using Value-Type Variables 11

C# Keywords

Keywords are reserved identifiers

Do not use keywords as variable names

Results in a compile-time error

Avoid using keywords by changing their case
sensitivity
abstract, base, bool, default, if, finally
abstract, base, bool, default, if, finally
int INT; // Poor style
int INT; // Poor style


*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Keywords are reserved, which means that you cannot use any keywords as
variable names in C#. Using a keyword as a variable name will result in a
compile-time error.
Keywords in C#
The following is a list of keywords in C#. Remember, you cannot use any of
these words as variable names.
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using virtual void
volatile while

Topic Objective
To list some of the most

common reserved
keywords.
Lead-in
Keywords are reserved
identifiers for the language
and cannot be used for
variable names.

×