Tải bản đầy đủ - 0 (trang)
Hour 12. Using Constants, Data Types, Variables, and Arrays

Hour 12. Using Constants, Data Types, Variables, and Arrays

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

Hour12.UsingConstants,DataTypes,

Variables,andArrays

AsyouwriteyourC#methods,you'llregularlyneedto

store and retrieve various pieces of information. In

fact, I can't think of a single application I've written

thatdidn'tneedtostoreandretrievedataincode.For

example, you might want to keep track of how many

times a method has been called, or you may want to

storeapropertyvalueanduseitatalatertime.Such

datacanbestoredasconstants,variables, or arrays.

Constants are named values that you define once at

design time but that can be referenced as often as

needed.Variables,ontheotherhand,arelikestorage

bins;youcanretrieveorreplacethedatainavariable

as often as you need to. Arrays act like grouped

variables, allowing you to store many values in a

singlearrayvariable.

Wheneveryoudefineoneofthesestorageentities,you

must decide the type of data it will contain. For

example, is a new variable going to hold a string

value (text) or perhaps a number? If it will hold a

number,isthenumberawholenumber,aninteger,or

something else entirely? After you determine the type

ofdatatostore,youmustchoosethelevelofvisibility

that the data has to other methods within the project

(this visibility is known as scope). In this hour, you'll

learn the ins and outs of C# new data types, how to



createandusethese"storage"mechanisms,andyou'll

learn how to minimize problems in your code by

reducingscope.

Thehighlightsofthishourincludethefollowing:

Understandingdatatypes

Determiningdatatype

Convertingdatatodifferentdatatypes

Definingandusingconstants

Dimensioningandreferencingvariables

Workingwitharrays

Determiningscope

Usinganamingconvention



I cover a lot of important material in this hour, but

you'llnoticealackofhands-onexamples.You'regoing

to use variables throughout the rest of this book, and

you'vealreadyusedtheminearlierhours.I'veusedthe

spaceinthishourtoteachyouthemeatofthesubject;

you'llgetexperiencewiththematerialinotherhours.







Top











UnderstandingDataTypes

Inanyprogramminglanguage,it'scriticalthatthecompiler,the

partoftheVisualStudioframeworkthatinterpretsthecodeyou

write into a language the computer can understand, fully

understands the type of data you're manipulating in code. For

example,ifyouaskedthecompilertoaddthefollowingvalues,

itwouldgetconfused:



659/"Dog"

When the compiler gets confused, it either refuses to

compile the code (which is the preferred situation

because you can address the problem before your

usersruntheapplication),oritwillhaltexecutionand

display an exception (error) when it reaches the

confusinglineofcode.(Thesetwotypesoferrorsare

discussed in detail in Hour 16, "Debugging Your

Code.")Obviously,youcan'tsubtract659bytheword

"Dog";thesetwovaluesaredifferenttypesofdata.In

C#, these two values are said to have two different

data types. In C#, constants, variables, and arrays

must always be defined to hold a specific type of

information.



DeterminingDataType



Data typing—the act of defining a constant, a

variable, or an array's data type—can be confusing.

To C#, a number is not a number. A number that

contains a decimal value is different from a number

thatdoesnot.C#canperformarithmeticonnumbers

ofdifferentdatatypes,butyoucan'tstoredataofone

typeinavariablewithanincompatibletype.Because

ofthislimitation,youmustgivecarefulconsideration

to the type of data you plan to store in a constant, a

variable, or an array at the time you define it. C#

supportstwocategoriesofdatatypes:valuetypesand

referencetypes.Themaindifferencebetweenthesetwo

typesishowtheirvaluesarestoredinmemory.Asyou

continue to create more complex applications, this

differencemayhaveanimpactonyourprogramming.

For this book, however, this distinction is minimal.

Table 12.1 lists the C# data types and the range of

valuestheycancontain.

Table12.1.TheC#DataTypes

Data

Type—

Value

bool

byte

char

decimal



ValueRange



trueorfalse

0to255

asinglecharacter

–79,228,162,514,264,337,593,543,950,335to–

7.9228162514264337593543950335.Usethisdata

typeforcurrencyvalues

double –1.79769313486232E308to–4.94065645841247E324fornegativevalues;4.94065645841247E–324to

1.79769313486232E308forpositivevalues



float



–3.402823E38to–1.401298E–45fornegativevalues;

1.401298E–45to3.402823E38forpositivevalues



int

long



–2,147,483,648to2,147,483,647.

–9,223,372,036,854,775,808to

9,223,372,036,854,775,807

–128to127

–32,768to32,767



sbyte

short



uint

Integersintherangefrom0to4,294,967,295

ulong Integersintherangefrom0to10^20

ushort Integersintherangefrom0to65,535

DataType—

Reference

string

object



ValueRange

0toapproximately2billioncharacters

Anytypecanbestoredinavariabletype

Object



C# supports unsigned data types for short, int, and long (the

typesprefaceswithu,suchasuint).Becausenegativenumbers

are excluded (there is no sign) this has the effect of doubling

the positive values for a short, an int, or a long. Signed data

typesarepreferableandshouldbeusedunlessyouhaveavery

good reason for doing otherwise (such as declaring a variable

thatwillneverholdanegativevalue).



TipsforDeterminingDataType

The list of data types may seem daunting at first, but you can

follow some general guidelines for choosing among them. As

you become more familiar with the different types, you'll be

abletofine-tuneyourdatatypeselection.

Followingaresomehelpfulguidelinesforusingdatatypes:



If you want to store text, use the string data type. The

string data type can be used to store any valid keyboard

character,includingnumbersandnonalphabeticcharacters.

If you want to store only the values true or false, use the

booldatatype.

If you want to store a number that contains no decimal

places and is greater than –32,768 and smaller than

32,767,usetheshortdatatype.

If you need to store numbers with no decimal places but

with values larger or smaller than short allows, use the int

orlongdatatypes.

If you need to store numbers that contain decimal places,

usethefloatdatatype.Thefloatdatatypeshouldworkfor

almost all your values containing decimals, unless you're

writing incredibly complex mathematical applications or

need to store very large numbers; in that case, use a

double.

If you need to store currency amounts, use the decimal

datatype.

If you need to store a single character, use the char data

type.



CastingDatafromOneDataTypetoAnother

Under some circumstances, C# won't allow you to

movedataofonetypeintoavariableofanothertype.

Theprocessofchangingavalue'sdatatypeisknown

ascasting.C#supportstwotypesofcasting:implicit

and explicit. Implicit conversions are done



automatically by the compiler. These conversions

guarantee that no data is lost in the conversion. For

instance,youcansetthevalueofavariabledeclared

asdoubletothevalueofavariabledeclaredasfloat

without an explicit cast because there is no risk of

losingdata;(thedoubledatatypeholdsahighervalue

thandoesafloat.

Explicitcastingisrequiredwhenapotentialexistsfordataloss

orwhenconvertingalargerdatatypeintoasmallerdatatype.

If you tried to place a value in a variable when the value was

higher than the variable's supported data type, some data

would be lost. Therefore, C# requires that these types of

conversions be explicitly written using the cast operator. For

instance, you can set the value of a variable declared as short

tothevalueofavariabledeclaredasintegerusingthefollowing

syntax:



shortMyShortInterger;

intMyInteger=1000;

MyShortInterger=(short)MyInteger;

Notice here that 1000 would fit in a short, so data wouldn't

actuallybelostifnoexplicitcastwereperformed.However,C#

doesn't care; it's the potential for data loss that causes C# to

requireexplicitcasts.

Table12.2listssomeofthetypeconversionsthatcanbedone

implicitlywithnolossofinformation.



Type

byte

short



Table12.2.SafeConversions

CanBeSafelyConvertedTo

char,short,int,long,float,double,decimal

int,long,float,double,decimal



int



long,float,double,decimal



long

float

double



float,double,decimal

double,decimal

decimal







Top











DefiningandUsingConstants

When you hard-code numbers in your code (such as in

intVotingAge = 19;), a myriad of things can go wrong. Hardcoded numbers are generally referred to as "magic numbers"

because they're often shrouded in mystery; the meaning of

suchanumberisobscurebecausethedigitsthemselvesgiveno

indication as to what the number represents. Constants are

usedtoeliminatetheproblemsofmagicnumbers.

Youdefineaconstantashavingaspecificvalueatdesigntime,

and that value never changes throughout the life of your

program.Constantsofferthefollowingbenefits:

Elimination or reduction of data entry problems It is much

easier,forexample,toremembertouseaconstantnamed

c_pithanitistoenter3.14159265358979everywherethat

pi is needed. The compiler will catch misspelled or

undeclared constants, but it doesn't care one bit what you

enter as a literal value. (Incidentally, you can retrieve the

value of pi using System.Math.PI, so you don't have to

worryaboutcreatingyourownconstant!)

Code is easier to update If you hard-coded a mortgage

interestrateat6.785,andrateswerechangedto7.00,you

wouldhavetochangeeveryoccurrenceof6.785incode.In

additiontothepossibilityofdataentryproblems,you'drun

theriskofchangingavalueof6.785thathadnothingtodo

with the interest rate—perhaps a value that represented a

savings bond yield. With a constant, you change the value

once,andallcodeusesthenewvalue.

Code is easier to read Magic numbers are often anything

butintuitive.Well-namedconstants,ontheotherhand,add



clarity to code. For example, which of the following

statementsmakesthemostsense?



decInterestAmount=((decLoanAmount*0.075)*12);

or



decInterestAmount=((decLoanAmount*c_fltInterestR

c_intMonthsInTerm);

Constantdefinitionshavethefollowingsyntax:



constdatatypename=value;

For example, to define a constant to hold the value of pi, you

coulduseastatementsuchasthis:



constfloatc_pi=3.14159265358979;

NotehowIprefixtheconstantnamewithc_.Idothissothat

it'seasiertodeterminewhat'savariableandwhat'saconstant

when reading code. See the section on naming conventions

laterinthishourformoreinformation.

After a constant is defined, you can use the constant's name

anywhereincodeinplaceoftheconstant'svalue.Forexample,

tooutputtheresultoftwotimesthevalueofpi,youcoulduse

astatementlikethis(the*characterisusedformultiplication

andiscoveredinthenexthour):



Debug.WriteLine(c_pi*2);

Using the constant is much easier and less error prone than

typingthis:



Debug.WriteLine(3.14159265358979*2);



Constantscanbereferencedonlyinthescopeinwhichtheyare

defined.Idiscussscopeinthesection"DeterminingScope."







Top



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

Hour 12. Using Constants, Data Types, Variables, and Arrays

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

×