71
Primitive Data Primitive Data Types and Types and Variables Variables Creating and Running Your First C# Creating and Running Your First C# Program Program Arshman Saleem Arshman Saleem Tech & Software Development Tech & Software Development

Primitive Data Types and Variables Lesson 02

Embed Size (px)

Citation preview

Page 1: Primitive Data Types and Variables Lesson 02

Primitive Data Primitive Data Types and Types and VariablesVariables

Creating and Running Your First C# Creating and Running Your First C# ProgramProgram

Arshman Arshman SaleemSaleemA Tech & Software DevelopmentA Tech & Software Development

Page 2: Primitive Data Types and Variables Lesson 02

Table of ContentsTable of Contents1.1. Primitive Data TypesPrimitive Data Types

Integer Integer Floating-Point / Decimal Floating-PointFloating-Point / Decimal Floating-Point BooleanBoolean CharacterCharacter StringString ObjectObject

2.2. Declaring and Using VariablesDeclaring and Using Variables IdentifiersIdentifiers Declaring Variables and Assigning ValuesDeclaring Variables and Assigning Values LiteralsLiterals

3.3. NullableNullable types types2

Page 3: Primitive Data Types and Variables Lesson 02

Primitive Data Primitive Data TypesTypes

Page 4: Primitive Data Types and Variables Lesson 02

How Computing Works?How Computing Works? Computers are machines that Computers are machines that

process dataprocess data Data is stored in the computer Data is stored in the computer

memory in memory in variablesvariables Variables have Variables have namename, , data type data type and and

valuevalue Example of variable definition and Example of variable definition and

assignment in C#assignment in C#int count = 5;int count = 5;Data Data typetype

Variable nameVariable name

Variable Variable valuevalue 4

Page 5: Primitive Data Types and Variables Lesson 02

What Is a Data Type?What Is a Data Type? A A data typedata type::

Is a domain of values of similar Is a domain of values of similar characteristicscharacteristics

Defines the type of information stored Defines the type of information stored in the computer memory (in a variable)in the computer memory (in a variable)

Examples:Examples: Positive integers: Positive integers: 11, , 22, , 33, , …… Alphabetical characters: Alphabetical characters: aa, , bb, , cc, , …… Days of week: Days of week: MondayMonday, , TuesdayTuesday, , ……

5

Page 6: Primitive Data Types and Variables Lesson 02

Data Type Data Type CharacteristicsCharacteristics

A data type has:A data type has: Name (C# keyword or .NET type)Name (C# keyword or .NET type) Size (how much memory is used)Size (how much memory is used) Default valueDefault value

Example:Example: Integer numbers in C#Integer numbers in C# Name: Name: intint Size: 32 bits (4 bytes)Size: 32 bits (4 bytes) Default value: 0Default value: 0

6

Page 7: Primitive Data Types and Variables Lesson 02

Integer TypesInteger Types

Page 8: Primitive Data Types and Variables Lesson 02

What are Integer What are Integer Types?Types?

Integer types:Integer types: Represent whole numbersRepresent whole numbers May be signed or unsignedMay be signed or unsigned Have range of values, depending on Have range of values, depending on

the size of memory usedthe size of memory used The default value of integer types The default value of integer types

is:is: 00 – for integer types, except – for integer types, except 0L0L – for the – for the longlong type type

8

Page 9: Primitive Data Types and Variables Lesson 02

Integer TypesInteger Types Integer types are:Integer types are:

sbytesbyte (-128 to 127): signed 8-bit (-128 to 127): signed 8-bit bytebyte (0 to 255): unsigned 8-bit (0 to 255): unsigned 8-bit shortshort (-32,768 to 32,767): signed 16- (-32,768 to 32,767): signed 16-

bitbit ushortushort (0 to 65,535): unsigned 16-bit (0 to 65,535): unsigned 16-bit intint (-2,147,483,648 to (-2,147,483,648 to

2,147,483,647): signed 32-bit2,147,483,647): signed 32-bit uintuint (0 to 4,294,967,295): unsigned (0 to 4,294,967,295): unsigned

32-bit32-bit9

Page 10: Primitive Data Types and Variables Lesson 02

Integer Types (2)Integer Types (2) More integer types:More integer types:

longlong (-9,223,372,036,854,775,808 to (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807): signed 9,223,372,036,854,775,807): signed 64-bit64-bit

ulongulong (0 to (0 to 18,446,744,073,709,551,615): 18,446,744,073,709,551,615): unsigned 64-bitunsigned 64-bit

10

Page 11: Primitive Data Types and Variables Lesson 02

Measuring Time – ExampleMeasuring Time – Example Depending on the unit of measure Depending on the unit of measure

we may use different data types:we may use different data types:

byte centuries = 20; // Usually a small byte centuries = 20; // Usually a small numbernumberushort years = 2000;ushort years = 2000;uint days = 730480;uint days = 730480;ulong hours = 17531520; // May be a very big ulong hours = 17531520; // May be a very big numbernumberConsole.WriteLine("{0} centuries is {1} years, Console.WriteLine("{0} centuries is {1} years, or {2} days, or {3} hours.", centuries, years, or {2} days, or {3} hours.", centuries, years, days, hours);days, hours);

11

Page 12: Primitive Data Types and Variables Lesson 02

Integer TypesInteger TypesLive DemoLive Demo

Page 13: Primitive Data Types and Variables Lesson 02

Floating-Point and Floating-Point and Decimal Floating-Decimal Floating-

Point TypesPoint Types

Page 14: Primitive Data Types and Variables Lesson 02

What are Floating-Point What are Floating-Point Types?Types?

Floating-point types:Floating-point types: Represent real numbersRepresent real numbers May be signed or unsignedMay be signed or unsigned Have range of values and different Have range of values and different

precision depending on the used precision depending on the used memorymemory

Can behave abnormally in the Can behave abnormally in the calculationscalculations

14

Page 15: Primitive Data Types and Variables Lesson 02

Floating-Point TypesFloating-Point Types Floating-point types are:Floating-point types are:

float float (±1.5 × 10(±1.5 × 10−45−45 to ±3.4 × 10 to ±3.4 × 103838): ): 32-bits, precision of 7 digits32-bits, precision of 7 digits

double double (±5.0 × 10(±5.0 × 10−324−324 to to ±1.7 × 10±1.7 × 10308308): 64-bits, precision of ): 64-bits, precision of 15-16 digits15-16 digits

The default value of floating-point The default value of floating-point types:types: Is Is 0.0F0.0F for the for the floatfloat typetype Is Is 0.0D0.0D for the for the doubledouble typetype

15

Page 16: Primitive Data Types and Variables Lesson 02

PI Precision – ExamplePI Precision – Example See below the difference in precision when See below the difference in precision when

using using floatfloat and and doubledouble::

NOTE: The “NOTE: The “ff” suffix in the first statement!” suffix in the first statement! Real numbers are by default interpreted as Real numbers are by default interpreted as doubledouble!!

One should One should explicitlyexplicitly convert them to convert them to floatfloat

float floatPI = 3.141592653589793238f;float floatPI = 3.141592653589793238f;double doublePI = 3.141592653589793238;double doublePI = 3.141592653589793238;Console.WriteLine("Float PI is: {0}", Console.WriteLine("Float PI is: {0}", floatPI);floatPI);Console.WriteLine("Double PI is: {0}", Console.WriteLine("Double PI is: {0}", doublePI);doublePI);

16

Page 17: Primitive Data Types and Variables Lesson 02

Abnormalities in the Abnormalities in the Floating-Point Floating-Point

CalculationsCalculations Sometimes abnormalities can be Sometimes abnormalities can be

observed when using floating-point observed when using floating-point numbersnumbers Comparing floating-point numbers Comparing floating-point numbers

can not be performed directly with can not be performed directly with the the ==== operator operator

Example:Example:double a = 1.0f;double a = 1.0f;double b = 0.33f;double b = 0.33f;double sum = 1.33f;double sum = 1.33f;bool equal = (a+b == sum); // False!!!bool equal = (a+b == sum); // False!!!Console.WriteLine("a+b={0} sum={1} Console.WriteLine("a+b={0} sum={1} equal={2}",equal={2}", a+b, sum, equal);a+b, sum, equal); 17

Page 18: Primitive Data Types and Variables Lesson 02

Decimal Floating-Point Decimal Floating-Point TypesTypes

There is a special decimal floating-There is a special decimal floating-pointpoint real number type in C#: real number type in C#: decimaldecimal (±1,0 × 10(±1,0 × 10-28-28 to ±7,9 × 10 to ±7,9 × 102828): ):

128-bits, precision of 28-29 digits128-bits, precision of 28-29 digits Used for financial calculationsUsed for financial calculations No round-off errorsNo round-off errors Almost no loss of precisionAlmost no loss of precision

The default value of The default value of decimaldecimal type is:type is: 0.00.0MM ( (MM is the suffix for decimal is the suffix for decimal

numbers)numbers)18

Page 19: Primitive Data Types and Variables Lesson 02

Floating-Point and Floating-Point and Decimal Floating-Decimal Floating-

Point TypesPoint TypesLive DemoLive Demo

Page 20: Primitive Data Types and Variables Lesson 02

Boolean TypeBoolean Type

Page 21: Primitive Data Types and Variables Lesson 02

The Boolean Data TypeThe Boolean Data Type The The Boolean data typeBoolean data type::

Is declared by the Is declared by the boolbool keyword keyword Has two possible values: Has two possible values: truetrue and and falsefalse

Is useful in logical expressionsIs useful in logical expressions The default value is The default value is falsefalse

21

Page 22: Primitive Data Types and Variables Lesson 02

Boolean Values – Boolean Values – ExampleExample

Example of boolean variables Example of boolean variables taking values of taking values of truetrue or or falsefalse::

int a = 1;int a = 1;int b = 2;int b = 2;

bool greaterAB = (a > b);bool greaterAB = (a > b);

Console.WriteLine(greaterAB); // FalseConsole.WriteLine(greaterAB); // False

bool equalA1 = (a == 1);bool equalA1 = (a == 1);

Console.WriteLine(equalA1); // TrueConsole.WriteLine(equalA1); // True

22

Page 23: Primitive Data Types and Variables Lesson 02

Boolean TypeBoolean TypeLive DemoLive Demo

Page 24: Primitive Data Types and Variables Lesson 02

Character TypeCharacter Type

Page 25: Primitive Data Types and Variables Lesson 02

The Character Data The Character Data TypeType

The The character data typecharacter data type:: Represents symbolic informationRepresents symbolic information Is declared by the Is declared by the charchar keyword keyword Gives each symbol a corresponding Gives each symbol a corresponding

integer codeinteger code Has a Has a '\0''\0' default value default value Takes 16 bits of memory (from Takes 16 bits of memory (from U+0000U+0000 to to U+FFFFU+FFFF))

25

Page 26: Primitive Data Types and Variables Lesson 02

Characters and CodesCharacters and Codes The example below shows that The example below shows that

every symbol has an its unique every symbol has an its unique Unicode code:Unicode code:char symbol = 'a';char symbol = 'a';Console.WriteLine("The code of '{0}' is: Console.WriteLine("The code of '{0}' is: {1}",{1}", symbol, (int) symbol);symbol, (int) symbol);

symbol = 'b';symbol = 'b';Console.WriteLine("The code of '{0}' is: Console.WriteLine("The code of '{0}' is: {1}",{1}", symbol, (int) symbol);symbol, (int) symbol);

symbol = 'A';symbol = 'A';Console.WriteLine("The code of '{0}' is: Console.WriteLine("The code of '{0}' is: {1}",{1}", symbol, (int) symbol);symbol, (int) symbol);

26

Page 27: Primitive Data Types and Variables Lesson 02

Character TypeCharacter TypeLive DemoLive Demo

Page 28: Primitive Data Types and Variables Lesson 02

String TypeString Type

Page 29: Primitive Data Types and Variables Lesson 02

The String Data TypeThe String Data Type The The string data typestring data type::

Represents a sequence of Represents a sequence of characterscharacters

Is declared by the Is declared by the stringstring keyword keyword Has a default value Has a default value nullnull (no value) (no value)

Strings are enclosed in quotes:Strings are enclosed in quotes:

Strings can be concatenatedStrings can be concatenated Using the Using the ++ operator operator

string s = "Microsoft .NET Framework";string s = "Microsoft .NET Framework";

29

Page 30: Primitive Data Types and Variables Lesson 02

Saying Hello – ExampleSaying Hello – Example Concatenating the two names of a Concatenating the two names of a

person to obtain his full name:person to obtain his full name:

NOTE: a space is missing between the NOTE: a space is missing between the two names! We have to add it two names! We have to add it manuallymanually

string firstName = "Ivan";string firstName = "Ivan";string lastName = "Ivanov";string lastName = "Ivanov";Console.WriteLine("Hello, {0}!\n", Console.WriteLine("Hello, {0}!\n", firstName);firstName);

string fullName = firstName + " " + string fullName = firstName + " " + lastName;lastName;Console.WriteLine("Your full name is {0}.",Console.WriteLine("Your full name is {0}.", fullName);fullName);

30

Page 31: Primitive Data Types and Variables Lesson 02

String TypeString TypeLive DemoLive Demo

Page 32: Primitive Data Types and Variables Lesson 02

Object TypeObject Type

Page 33: Primitive Data Types and Variables Lesson 02

The Object TypeThe Object Type The object type:The object type:

Is declared by the Is declared by the objectobject keyword keyword Is the base type of all other typesIs the base type of all other types Can hold values of any typeCan hold values of any type

33

Page 34: Primitive Data Types and Variables Lesson 02

Using ObjectsUsing Objects Example of an object variable Example of an object variable

taking different types of data:taking different types of data:object dataContainer = 5;object dataContainer = 5;Console.Write("The value of dataContainer is: Console.Write("The value of dataContainer is: ");");Console.WriteLine(dataContainer);Console.WriteLine(dataContainer);

dataContainer = "Five";dataContainer = "Five";Console.Write("The value of dataContainer is: Console.Write("The value of dataContainer is: ");");Console.WriteLine(dataContainer);Console.WriteLine(dataContainer);

34

Page 35: Primitive Data Types and Variables Lesson 02

ObjectsObjectsLive DemoLive Demo

Page 36: Primitive Data Types and Variables Lesson 02

Introducing Introducing VariablesVariables

pp qqii

Page 37: Primitive Data Types and Variables Lesson 02

What Is a Variable?What Is a Variable? A variable is a:A variable is a:

Placeholder of information that can Placeholder of information that can usually be changed at run-timeusually be changed at run-time

Variables allow you to:Variables allow you to: Store informationStore information Retrieve the stored informationRetrieve the stored information Manipulate the stored informationManipulate the stored information

37

Page 38: Primitive Data Types and Variables Lesson 02

Variable CharacteristicsVariable Characteristics A variable has:A variable has:

NameName Type (of stored data)Type (of stored data) ValueValue

Example:Example:

Name: Name: countercounter Type: Type: intint Value: Value: 55

int counter = 5;int counter = 5;

38

Page 39: Primitive Data Types and Variables Lesson 02

Declaring And Declaring And Using VariablesUsing Variables

Page 40: Primitive Data Types and Variables Lesson 02

Declaring VariablesDeclaring Variables When declaring a variable we:When declaring a variable we:

Specify its typeSpecify its type Specify its name (called identifier)Specify its name (called identifier) May give it an initial valueMay give it an initial value

The syntax is the following:The syntax is the following:

Example:Example:<data_type> <identifier> [= <initialization>];<data_type> <identifier> [= <initialization>];

int height = 200;int height = 200;

40

Page 41: Primitive Data Types and Variables Lesson 02

IdentifiersIdentifiers Identifiers may consist of:Identifiers may consist of:

Letters (Unicode) Letters (Unicode) Digits [0-9]Digits [0-9] Underscore "_"Underscore "_"

IdentifiersIdentifiers Can begin only with a letter or an Can begin only with a letter or an

underscoreunderscore Cannot be a C# keywordCannot be a C# keyword

41

Page 42: Primitive Data Types and Variables Lesson 02

Identifiers (2)Identifiers (2) IdentifiersIdentifiers

Should have a descriptive nameShould have a descriptive name It is recommended to use only Latin It is recommended to use only Latin

lettersletters Should be neither too long nor too Should be neither too long nor too

shortshort Note:Note:

In C# small letters are considered In C# small letters are considered different than the capital letters different than the capital letters (case sensitivity)(case sensitivity)

42

Page 43: Primitive Data Types and Variables Lesson 02

Identifiers – ExamplesIdentifiers – Examples Examples of correct identifiers:Examples of correct identifiers:

Examples of incorrect identifiers:Examples of incorrect identifiers:int new;int new; // new is a keyword// new is a keywordint 2Pac;int 2Pac; // Cannot begin with a digit// Cannot begin with a digit

int New = 2; // Here N is capitalint New = 2; // Here N is capitalint _2Pac; // This identifiers begins with _int _2Pac; // This identifiers begins with _

string поздрав = "Hello"; // Unicode symbols usedstring поздрав = "Hello"; // Unicode symbols used// The following is more appropriate:// The following is more appropriate:string greeting = "Hello"; string greeting = "Hello";

int n = 100; // Undescriptiveint n = 100; // Undescriptiveint numberOfClients = 100; // Descriptiveint numberOfClients = 100; // Descriptive

// Overdescriptive identifier:// Overdescriptive identifier:int numberOfPrivateClientOfTheFirm = 100;int numberOfPrivateClientOfTheFirm = 100;

43

Page 44: Primitive Data Types and Variables Lesson 02

Assigning Assigning Values To Values To VariablesVariables

Page 45: Primitive Data Types and Variables Lesson 02

Assigning ValuesAssigning Values Assigning of values to variablesAssigning of values to variables

Is achieved by the Is achieved by the == operator operator The The == operator has operator has

Variable identifier on the leftVariable identifier on the left Value of the corresponding data Value of the corresponding data

type on the righttype on the right Could be used in a cascade calling, Could be used in a cascade calling,

where assigning is done from right where assigning is done from right to leftto left

45

Page 46: Primitive Data Types and Variables Lesson 02

Assigning Values – Assigning Values – ExamplesExamples

Assigning values example:Assigning values example:int firstValue = 5;int firstValue = 5;int secondValue;int secondValue;int thirdValue;int thirdValue;

// Using an already declared variable:// Using an already declared variable:secondValue = firstValue;secondValue = firstValue;

// The following cascade calling assigns// The following cascade calling assigns// 3 to firstValue and then firstValue// 3 to firstValue and then firstValue// to thirdValue, so both variables have// to thirdValue, so both variables have// the value 3 as a result:// the value 3 as a result:

thirdValue = firstValue = 3; // Avoid this!thirdValue = firstValue = 3; // Avoid this!

46

Page 47: Primitive Data Types and Variables Lesson 02

Initializing VariablesInitializing Variables InitializingInitializing

Is assigning of initial valueIs assigning of initial value Must be done before the variable is Must be done before the variable is

used!used! Several ways of initializing:Several ways of initializing:

By using the By using the newnew keyword keyword By using a literal expressionBy using a literal expression By referring to an already initialized By referring to an already initialized

variablevariable47

Page 48: Primitive Data Types and Variables Lesson 02

Initialization – Initialization – ExamplesExamples

Example of some initializations:Example of some initializations:

// The following would assign the default// The following would assign the default// value of the int type to num:// value of the int type to num:int num = new int(); // num = 0int num = new int(); // num = 0

// This is how we use a literal expression:// This is how we use a literal expression:float heightInMeters = 1.74f;float heightInMeters = 1.74f;

// Here we use an already initialized // Here we use an already initialized variable:variable:string greeting = "Hello World!";string greeting = "Hello World!";string message = greeting;string message = greeting;

48

Page 49: Primitive Data Types and Variables Lesson 02

Assigning and Assigning and Initializing Initializing VariablesVariables

Live DemoLive Demo

Page 50: Primitive Data Types and Variables Lesson 02

LiteralsLiterals

Page 51: Primitive Data Types and Variables Lesson 02

What are Literals?What are Literals? Literals are:Literals are:

Representations of values in the Representations of values in the source codesource code

There are six types of literalsThere are six types of literals BooleanBoolean IntegerInteger RealReal CharacterCharacter StringString The The nullnull literal literal

51

Page 52: Primitive Data Types and Variables Lesson 02

Boolean and Integer Boolean and Integer LiteralsLiterals

The boolean literals are:The boolean literals are: truetrue falsefalse

The integer literals:The integer literals: Are used for variables of type Are used for variables of type intint, , uintuint, , longlong, and , and ulongulong

Consist of digitsConsist of digits May have a sign (May have a sign (++,,--)) May be in a hexadecimal formatMay be in a hexadecimal format

52

Page 53: Primitive Data Types and Variables Lesson 02

Integer LiteralsInteger Literals Examples of integer literalsExamples of integer literals

The The ''0x0x'' and and ''0X0X'' prefixes mean a prefixes mean a hexadecimal value, e.g. hexadecimal value, e.g. 0xA8F10xA8F1

The The ''uu'' and and ''UU'' suffixes mean a suffixes mean a ulongulong or or uintuint type, e.g. type, e.g. 12345678U12345678U

The The ''ll'' and and ''LL'' suffixes mean a suffixes mean a longlong or or ulongulong type, e.g. type, e.g. 9876543L9876543L

53

Page 54: Primitive Data Types and Variables Lesson 02

Integer Literals – Integer Literals – ExampleExample

Note: the letter ‘Note: the letter ‘ll’ is easily confused with ’ is easily confused with the digit ‘the digit ‘11’ so it’s better to use ‘’ so it’s better to use ‘LL’!!!’!!!

// The following variables are// The following variables are// initialized with the same value:// initialized with the same value:int numberInHex = -0x10;int numberInHex = -0x10;int numberInDec = -16;int numberInDec = -16;

// The following causes an error,// The following causes an error,because 234u is of type uintbecause 234u is of type uintint unsignedInt = 234u;int unsignedInt = 234u;

// The following causes an error,// The following causes an error,because 234L is of type longbecause 234L is of type longint longInt = 234L;int longInt = 234L;

54

Page 55: Primitive Data Types and Variables Lesson 02

Real LiteralsReal Literals The real literals:The real literals:

Are used for values of type Are used for values of type floatfloat, , doubledouble and and decimaldecimal

May consist of digits, a sign and “May consist of digits, a sign and “..”” May be in exponential notation: May be in exponential notation: 6.02e+236.02e+23

The “The “ff” and “” and “FF” suffixes mean ” suffixes mean floatfloat The “The “dd” and “” and “DD” suffixes mean ” suffixes mean doubledouble The “The “mm” and “” and “MM” suffixes mean ” suffixes mean decimaldecimal The default interpretation is The default interpretation is doubledouble

55

Page 56: Primitive Data Types and Variables Lesson 02

Real Literals – ExampleReal Literals – Example Example of incorrect Example of incorrect floatfloat literal: literal:

A correct way to assign floating-A correct way to assign floating-point value (using also the point value (using also the exponential format):exponential format):

56

// The following causes an error// The following causes an error// because 12.5 is double by default// because 12.5 is double by defaultfloat realNumber = 12.5;float realNumber = 12.5;

// The following is the correct// The following is the correct// way of assigning the value:// way of assigning the value:float realNumber = 12.5f;float realNumber = 12.5f;

// This is the same value in exponential format:// This is the same value in exponential format:realNumber = 1.25e+7f;realNumber = 1.25e+7f;

Page 57: Primitive Data Types and Variables Lesson 02

Character LiteralsCharacter Literals The character literals:The character literals:

Are used for values of the Are used for values of the charchar typetype Consist of two single quotes Consist of two single quotes

surrounding the character value: surrounding the character value: ''<value><value>''

The value may be:The value may be: SymbolSymbol The code of the symbolThe code of the symbol Escaping sequenceEscaping sequence

57

Page 58: Primitive Data Types and Variables Lesson 02

Escaping SequencesEscaping Sequences Escaping sequences are:Escaping sequences are:

Means of presenting a symbol that is Means of presenting a symbol that is usually interpreted otherwise (like usually interpreted otherwise (like ''))

Means of presenting system symbols Means of presenting system symbols (like the new line symbol)(like the new line symbol)

Common escaping sequences are:Common escaping sequences are: \'\' for single quote for single quote \"\" for double quote for double quote \\\\ for backslash for backslash \n\n for new linefor new line \uXXXX\uXXXX for denoting any other Unicode for denoting any other Unicode

symbolsymbol58

Page 59: Primitive Data Types and Variables Lesson 02

Character Literals – Character Literals – ExampleExample

Examples of different character Examples of different character literals:literals:char symbol = 'a'; // An ordinary symbolchar symbol = 'a'; // An ordinary symbol

symbol = '\u006F'; // Unicode symbol code in symbol = '\u006F'; // Unicode symbol code in // a hexadecimal format // a hexadecimal format

symbol = '\u8449'; // symbol = '\u8449'; // 葉 葉 ((Leaf in Traditional Leaf in Traditional Chinese)Chinese)

symbol = '\''; // Assigning the single quote symbol = '\''; // Assigning the single quote symbolsymbol

symbol = '\\'; // Assigning the backslash symbolsymbol = '\\'; // Assigning the backslash symbol

symbol = '\n'; // Assigning new line symbolsymbol = '\n'; // Assigning new line symbol

symbol = '\t'; // Assigning TAB symbolsymbol = '\t'; // Assigning TAB symbol

symbol = "a"; // Incorrect: use single quotessymbol = "a"; // Incorrect: use single quotes 59

Page 60: Primitive Data Types and Variables Lesson 02

String LiteralsString Literals String literals:String literals:

Are used for values of the string Are used for values of the string typetype

Consist of two double quotes Consist of two double quotes surrounding the value: surrounding the value: ""<value><value>""

May have a May have a @@ prefix which ignores prefix which ignores the used escaping sequences: the used escaping sequences: @@"<value>""<value>"

The value is a sequence of The value is a sequence of character literalscharacter literalsstring s = "I am a sting literal";string s = "I am a sting literal";

60

Page 61: Primitive Data Types and Variables Lesson 02

String Literals – String Literals – ExampleExample

Benefits of quoted strings (the Benefits of quoted strings (the @@ prefix):prefix):

In quoted strings In quoted strings \"\" is used instead of is used instead of """"!!

// Here is a string literal using escape sequences// Here is a string literal using escape sequencesstring quotation = "\"Hello, Jude\", he said.";string quotation = "\"Hello, Jude\", he said.";string path = "C:\\WINNT\\Darts\\Darts.exe";string path = "C:\\WINNT\\Darts\\Darts.exe";

// Here is an example of the usage of @// Here is an example of the usage of @quotation = @"""Hello, Jimmy!"", she answered.";quotation = @"""Hello, Jimmy!"", she answered.";path = @"C:\WINNT\Darts\Darts.exe";path = @"C:\WINNT\Darts\Darts.exe";

string str = @"somestring str = @"sometext";text";

61

Page 62: Primitive Data Types and Variables Lesson 02

String LiteralsString LiteralsLive DemoLive Demo

Page 63: Primitive Data Types and Variables Lesson 02

Nullable TypesNullable Types

63

Page 64: Primitive Data Types and Variables Lesson 02

Nullable TypesNullable Types NullableNullable types are instances of the types are instances of the System.NullableSystem.Nullable structstruct Wrapper over the Wrapper over the primitiveprimitive typestypes E.g. E.g. int?int?, , double?double?, etc., etc.

NullabeNullabe type can represent the normal type can represent the normal range of values for its underlying range of values for its underlying value type, plus an additional value type, plus an additional nullnull valuevalue

Useful when dealing with Useful when dealing with DatabasesDatabases or or other structures that have default other structures that have default value value nullnull

Page 65: Primitive Data Types and Variables Lesson 02

Nullable Types – Nullable Types – ExampleExample

int? someInteger = null;int? someInteger = null;Console.WriteLine(Console.WriteLine( "This is the integer with Null value -> " + "This is the integer with Null value -> " + someInteger);someInteger);someInteger = 5;someInteger = 5;Console.WriteLine(Console.WriteLine( "This is the integer with value 5 -> " + "This is the integer with value 5 -> " + someInteger);someInteger);

double? someDouble = null;double? someDouble = null;Console.WriteLine(Console.WriteLine( "This is the real number with Null value -> " "This is the real number with Null value -> " + someDouble);+ someDouble);someDouble = 2.5;someDouble = 2.5;Console.WriteLine(Console.WriteLine( "This is the real number with value 5 -> " + "This is the real number with value 5 -> " + someDouble);someDouble);

Example with Example with IntegerInteger::

Example with Example with DoubleDouble::

Page 66: Primitive Data Types and Variables Lesson 02

Nullable TypesNullable TypesLive DemoLive Demo

66

Page 67: Primitive Data Types and Variables Lesson 02

QuestionsQuestions??

Primitive Data Primitive Data Types and Types and VariablesVariables

http://academy.telerik.com

Page 68: Primitive Data Types and Variables Lesson 02

ExercisesExercises1.1. Declare five variables choosing for each of Declare five variables choosing for each of

them the most appropriate of the types them the most appropriate of the types bytebyte, , sbytesbyte, , shortshort, , ushortushort, , intint, , uintuint, , longlong, , ulongulong to to represent the following values: 52130, -115, represent the following values: 52130, -115, 4825932, 97, -10000.4825932, 97, -10000.

2.2. Which of the following values can be assigned Which of the following values can be assigned to a variable of type to a variable of type floatfloat and which to a and which to a variable of type variable of type doubledouble: 34.567839023, : 34.567839023, 12.345, 8923.1234857, 3456.091?12.345, 8923.1234857, 3456.091?

3.3. Write a program that safely compares Write a program that safely compares floating-point numbers with precision of floating-point numbers with precision of 0.0000010.000001..

68

Page 69: Primitive Data Types and Variables Lesson 02

Exercises (2)Exercises (2)4.4. Declare an integer variable and assign it Declare an integer variable and assign it

with the value 254 in hexadecimal format. with the value 254 in hexadecimal format. Use Windows Calculator to find its Use Windows Calculator to find its hexadecimal representation.hexadecimal representation.

5.5. Declare a character variable and assign it Declare a character variable and assign it with the symbol that has Unicode code 72. with the symbol that has Unicode code 72. Hint: first use the Windows Calculator to Hint: first use the Windows Calculator to find the hexadecimal representation of 72.find the hexadecimal representation of 72.

6.6. Declare a boolean variable called Declare a boolean variable called isFemaleisFemale and assign an appropriate value and assign an appropriate value corresponding to your gender.corresponding to your gender.

69

Page 70: Primitive Data Types and Variables Lesson 02

Exercises (3)Exercises (3)7.7. Declare two Declare two stringstring variables and assign them variables and assign them

with “Hello” and “World”. Declare an with “Hello” and “World”. Declare an objectobject variable and assign it with the concatenation variable and assign it with the concatenation of the first two variables (mind adding an of the first two variables (mind adding an interval). Declare a third interval). Declare a third stringstring variable and variable and initialize it with the value of the object initialize it with the value of the object variable (you should perform type casting).variable (you should perform type casting).

8.8. Declare two Declare two stringstring variables and assign them variables and assign them with following value:with following value:

Do the above in two different ways: with and Do the above in two different ways: with and without using quoted strings.without using quoted strings.

The "use" of quotations causes difficulties. The "use" of quotations causes difficulties.

70

Page 71: Primitive Data Types and Variables Lesson 02

Exercises (4)Exercises (4)9.9. Write a program thatWrite a program that prints an isosceles prints an isosceles

triangle of 9 copyright symbols triangle of 9 copyright symbols ©©. Use . Use Windows Character Map to find the Unicode Windows Character Map to find the Unicode code of the code of the ©© symbol. symbol.

10.10. A marketing firm wants to keep record of its A marketing firm wants to keep record of its employees. Each record would have the employees. Each record would have the following characteristics – first name, family following characteristics – first name, family name,name, age,age, gender (m or f), ID number,gender (m or f), ID number, unique unique employee number (27560000 to 27569999). employee number (27560000 to 27569999). Declare the variables needed to keep the Declare the variables needed to keep the information for a single employee using information for a single employee using appropriate data typesappropriate data types andand descriptive names.descriptive names.

11.11. Declare two integer variables and assign Declare two integer variables and assign them with 5 and 10 and after that exchange them with 5 and 10 and after that exchange their values.their values.

71