
PrimitivePrimitive DataData TypesTypes andand VariablesVariables CreatingCreating andand RunningRunning YourYour FirstFirst C#C# ProgramProgram SvetlinSvetlin NakovNakov Telerik Corporation www.telerik.com TableTable ofof ContentsContents 1. PrimitivePrimitive DataData TypesTypes IntegerInteger Floating-PointFloating-Point // DecimalDecimal Floating-PointFloating-Point BooleanBoolean CharacterCharacter StringString ObjectObject 2. DeclaringDeclaring andand UsingUsing VariablesVariables IdentifiersIdentifiers DeclaringDeclaring VariablesVariables andand AssigningAssigning ValuesValues LiteralsLiterals P NullableNullable typestypes 2 PrimitivePrimitive DataData TypesTypes HowHow ComputingComputing Works?Works? ComputersComputers areare machinesmachines thatthat processprocess datadata DataData isis storedstored inin thethe computercomputer memorymemory inin variablesvariables VariablesVariables havehave namename,, datadata typetype andand valuevalue ExampleExample ofof variablevariable definitiondefinition andand assignmentassignment inin C#C# VariableVariable namename DataData typetype int count = 5; VariableVariable valuevalue 4 WhatWhat IsIs aa DataData Type?Type? AA datadata typetype:: IsIs aa domaindomain ofof valuesvalues ofof similarsimilar characteristicscharacteristics DefinesDefines thethe typetype ofof informationinformation storedstored inin thethe computercomputer memorymemory (in(in aa variable)variable) Examples:Examples: PositivePositive integers:integers: 11,, 22,, 33,, …… AlphabeticalAlphabetical characters:characters: aa,, bb,, cc,, …… DaysDays ofof week:week: MondayMonday,, TuesdayTuesday,, …… 5 DataData TypeType CharacteristicsCharacteristics AA datadata typetype has:has: NameName (C#(C# keywordkeyword oror .NET.NET type)type) SizeSize (how(how muchmuch memorymemory isis used)used) DefaultDefault valuevalue Example:Example: IntegerInteger numbersnumbers inin C#C# Name:Name: intint Size:Size: 3232 bitsbits (4(4 bytes)bytes) DefaultDefault value:value: 00 6 IntegerInteger TypesTypes WhatWhat areare IntegerInteger Types?Types? IntegerInteger types:types: RepresentRepresent wholewhole numbersnumbers MayMay bebe signedsigned oror unsignedunsigned HaveHave rangerange ofof values,values, dependingdepending onon thethe sizesize ofof memorymemory usedused TheThe defaultdefault valuevalue ofof integerinteger typestypes is:is: 00 –– forfor integerinteger types,types, exceptexcept 0L0L –– forfor thethe longlong typetype 8 IntegerInteger TypesTypes IntegerInteger typestypes are:are: sbytesbyte (-128(-128 toto 127):127): signedsigned 8-bit8-bit bytebyte (0(0 toto 255):255): unsignedunsigned 8-bit8-bit shortshort (-32,768(-32,768 toto 32,767):32,767): signedsigned 16-bit16-bit ushortushort (0(0 toto 65,535):65,535): unsignedunsigned 16-bit16-bit intint (-2,147,483,648(-2,147,483,648 toto 2,147,483,647):2,147,483,647): signedsigned 32-bit32-bit uintuint (0(0 toto 4,294,967,295):4,294,967,295): unsignedunsigned 32-bit32-bit 9 IntegerInteger TypesTypes (2)(2) MoreMore integerinteger types:types: longlong (-9,223,372,036,854,775,808(-9,223,372,036,854,775,808 toto 9,223,372,036,854,775,807):9,223,372,036,854,775,807): signedsigned 64-bit64-bit ulongulong (0(0 toto 18,446,744,073,709,551,615):18,446,744,073,709,551,615): unsignedunsigned 64-bit64-bit 10 MeasuringMeasuring TimeTime –– ExampleExample DependingDepending onon thethe unitunit ofof measuremeasure wewe maymay useuse differentdifferent datadata types:types: byte centuries = 20; // Usually a small number ushort years = 2000; uint days = 730480; ulong hours = 17531520; // May be a very big number Console.WriteLine("{0} centuries is {1} years, or {2} days, or {3} hours.", centuries, years, days, hours); 11 IntegerInteger TypesTypes LiveLive DemoDemo Floating-PointFloating-Point andand DecimalDecimal Floating-PointFloating-Point TypesTypes WhatWhat areare Floating-PointFloating-Point Types?Types? Floating-pointFloating-point types:types: RepresentRepresent realreal numbersnumbers MayMay bebe signedsigned oror unsignedunsigned HaveHave rangerange ofof valuesvalues andand differentdifferent precisionprecision dependingdepending onon thethe usedused memorymemory CanCan behavebehave abnormallyabnormally inin thethe calculationscalculations 14 Floating-PointFloating-Point TypesTypes Floating-pointFloating-point typestypes are:are: floatfloat (±1.5(±1.5 ×× 1010−45 toto ±3.4±3.4 ×× 101038):): 32-bits,32-bits, precisionprecision ofof 77 digitsdigits doubledouble (±5.0(±5.0 ×× 1010−324 toto ±1.7±1.7 ×× 1010308):): 64-bits,64-bits, precisionprecision ofof 15-1615-16 digitsdigits TheThe defaultdefault valuevalue ofof floating-pointfloating-point types:types: IsIs 0.0F0.0F forfor thethe floatfloat typetype IsIs 0.0D0.0D forfor thethe doubledouble typetype 15 PIPI PrecisionPrecision –– ExampleExample SeeSee belowbelow thethe differencedifference inin precisionprecision whenwhen usingusing floatfloat andand doubledouble:: float floatPIfloatPI = 3.141592653589793238f; double doublePI = 3.141592653589793238; Console.WriteLine("Float PI is: {0}", floatPI); Console.WriteLine("Double PI is: {0}", doublePI); NOTE:NOTE: TheThe ““ff”” suffixsuffix inin thethe firstfirst statement!statement! RealReal numbersnumbers areare byby defaultdefault interpretedinterpreted asas doubledouble!! OneOne shouldshould explicitlyexplicitly convertconvert themthem toto floatfloat 16 AbnormalitiesAbnormalities inin thethe Floating-PointFloating-Point CalculationsCalculations SometimesSometimes abnormalitiesabnormalities cancan bebe observedobserved whenwhen usingusing floating-pointfloating-point numbersnumbers ComparingComparing floating-pointfloating-point numbersnumbers cancan notnot bebe performedperformed directlydirectly withwith thethe ==== operatoroperator Example:Example: double a = 1.0f; double b = 0.33f; double sum = 1.33f; bool equal = (a+b == sum); // False!!! Console.WriteLine("a+b={0} sum={1} equal={2}", a+b, sum, equal); 17 DecimalDecimal Floating-PointFloating-Point TypesTypes ThereThere isis aa specialspecial decimaldecimal floating-pointfloating-point realreal numbernumber typetype inin C#:C#: decimaldecimal (±1,0(±1,0 ×× 1010-28 toto ±7,9±7,9 ×× 101028):): 128-bits,128-bits, precisionprecision ofof 28-2928-29 digitsdigits UsedUsed forfor financialfinancial calculationscalculations NoNo round-offround-off errorserrors AlmostAlmost nono lossloss ofof precisionprecision TheThe defaultdefault valuevalue ofof decimaldecimal typetype is:is: 0.00.0MM ((MM isis thethe suffixsuffix forfor decimaldecimal numbers)numbers) 18 Floating-PointFloating-Point andand DecimalDecimal Floating-PointFloating-Point TypesTypes LiveLive DemoDemo BooleanBoolean TypeType TheThe BooleanBoolean DataData TypeType TheThe BooleanBoolean datadata typetype:: IsIs declareddeclared byby thethe boolbool keywordkeyword HasHas twotwo possiblepossible values:values: truetrue andand falsefalse IsIs usefuluseful inin logicallogical expressionsexpressions TheThe defaultdefault valuevalue isis falsefalse 21 BooleanBoolean ValuesValues –– ExampleExample ExampleExample ofof booleanboolean variablesvariables takingtaking valuesvalues ofof truetrue oror falsefalse:: int a = 1; int b = 2; bool greaterAB = (a > b); Console.WriteLine(greaterAB); // False bool equalA1 = (a == 1); Console.WriteLine(equalA1); // True 22 BooleanBoolean TypeType LiveLive DemoDemo CharacterCharacter TypeType TheThe CharacterCharacter DataData TypeType TheThe charactercharacter datadata typetype:: RepresentsRepresents symbolicsymbolic informationinformation IsIs declareddeclared byby thethe charchar keywordkeyword GivesGives eacheach symbolsymbol aa correspondingcorresponding integerinteger codecode HasHas aa '\0''\0' defaultdefault valuevalue TakesTakes 1616 bitsbits ofof memorymemory (from(from U+0000U+0000 toto U+FFFFU+FFFF)) 25 CharactersCharacters andand CodesCodes TheThe exampleexample belowbelow showsshows thatthat everyevery symbolsymbol hashas anan itsits uniqueunique UnicodeUnicode code:code: char symbol = 'a'; Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol); symbol = 'b'; Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol); symbol = 'A'; Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol); 26 CharacterCharacter TypeType LiveLive DemoDemo StringString TypeType TheThe StringString DataData TypeType TheThe stringstring datadata typetype:: RepresentsRepresents aa sequencesequence ofof characterscharacters IsIs declareddeclared byby thethe stringstring keywordkeyword HasHas aa defaultdefault valuevalue nullnull (no(no value)value) StringsStrings areare enclosedenclosed inin quotes:quotes: string s = "Microsoft .NET Framework"; StringsStrings cancan bebe concatenatedconcatenated UsingUsing thethe ++ operatoroperator 29 SayingSaying HelloHello –– ExampleExample ConcatenatingConcatenating thethe twotwo namesnames ofof aa personperson toto obtainobtain hishis fullfull name:name: string firstName = "Ivan"; string lastName = "Ivanov"; Console.WriteLine("Hello, {0}!\n", firstName); string fullName = firstName + " " + lastName; Console.WriteLine("Your full name is {0}.", fullName); NOTE:NOTE: aa spacespace isis missingmissing betweenbetween thethe twotwo names!names! WeWe havehave toto addadd itit manuallymanually 30 StringString TypeType LiveLive DemoDemo ObjectObject TypeType TheThe ObjectObject TypeType TheThe objectobject type:type: IsIs declareddeclared byby thethe objectobject keywordkeyword IsIs thethe
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages71 Page
-
File Size-