11.. primitive data types and variables - eemb · pdf file10/3/2011 1 primitive data types and...
TRANSCRIPT
10/3/2011
1
Primitive Data Primitive Data Types and VariablesTypes and Variables
Creating and Running Your First C# ProgramCreating and Running Your First C# Program
Table of ContentsTable of Contents
1.1. Primitive Data TypesPrimitive Data Types
�� Integer Integer
�� FloatingFloating--Point / Decimal FloatingPoint / Decimal Floating--PointPoint
�� 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 typestypes
2
Primitive Data TypesPrimitive Data Types
How Computing Works?How Computing Works?
�� Computers are machines that process dataComputers are machines that process data
�� Data is stored in the computer memory in Data is stored in the computer memory in
variablesvariables
�� Variables have Variables have namename, , data type data type and and valuevalue
�� Example of variable definition and assignment Example of variable definition and assignment
in C#in C#
int count = 5;int count = 5;Data typeData type
Variable nameVariable name
Variable valueVariable value4
What Is a Data Type?What Is a Data Type?
�� A A data typedata type::
�� Is a domain of values of similar characteristicsIs a domain of values of similar characteristics
�� Defines the type of information stored in the Defines the type of information stored in the
computer memory (in a variable)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
Data Type CharacteristicsData Type Characteristics
�� A data type has:A data type has:
�� Name (C# Name (C# keyword or .NET type)keyword or .NET type)
�� Size (how much memory is used)Size (how much memory is used)
�� Default Default valuevalue
�� 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
10/3/2011
2
Integer TypesInteger Types
What are Integer Types?What are Integer 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 the Have range of values, depending on the size of size of
memory usedmemory used
�� The default value of integer types is:The default value of integer types is:
�� 00 –– for integer types, exceptfor integer types, except
�� 0L0L –– for the for the longlong typetype
8
Integer TypesInteger Types
�� Integer types are:Integer types are:
�� sbytesbyte ((--128 to 127): signed 8128 to 127): signed 8--bitbit
�� bytebyte (0 to 255): unsigned 8(0 to 255): unsigned 8--bitbit
�� shortshort ((--32,768 to 32,767): signed 1632,768 to 32,767): signed 16--bitbit
�� ushortushort (0 to 65,535): unsigned (0 to 65,535): unsigned 1616--bitbit
�� intint ((--2,147,483,648 to 2,147,483,647): signed 2,147,483,648 to 2,147,483,647): signed
3232--bitbit
�� uintuint (0 to 4,294,967,295): unsigned 32(0 to 4,294,967,295): unsigned 32--bitbit
9
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 649,223,372,036,854,775,807): signed 64--bitbit
�� ulongulong (0 to 18,446,744,073,709,551,615): (0 to 18,446,744,073,709,551,615):
unsigned 64unsigned 64--bitbit
10
Measuring Time Measuring Time –– ExampleExample
�� Depending on the unit of measure we may use Depending on the unit of measure we may use different data types:different data types:
byte centuries = 20; // Usually a small numberbyte centuries = 20; // Usually a small number
ushort years = 2000;ushort years = 2000;
uint days = 730480;uint days = 730480;
ulong hours = 17531520; // May be a very big numberulong hours = 17531520; // May be a very big number
Console.WriteLine("{0} centuries is {1} years, or {2} Console.WriteLine("{0} centuries is {1} years, or {2}
days, or {3} hours.", centuries, years, days, hours);days, or {3} hours.", centuries, years, days, hours);
11
Integer TypesInteger TypesExamples 02Examples 02--01;0201;02--0202
10/3/2011
3
FloatingFloating--Point and Decimal Point and Decimal FloatingFloating--Point TypesPoint Types
What are FloatingWhat are Floating--Point Types?Point Types?
�� FloatingFloating--point types:point types:
�� Represent real numbersRepresent real numbers
�� May be signed or unsignedMay be signed or unsigned
�� Have range of values and different precision Have range of values and different precision
depending on the used memorydepending on the used memory
�� Can behave abnormally in the calculationsCan behave abnormally in the calculations
14
FloatingFloating--Point TypesPoint Types
�� FloatingFloating--point types are:point types are:
�� float float ((±±1.51.5 ×× 1010−45−45 to to ±±3.43.4 ×× 10103838): 32): 32--bits, bits,
precision of 7 digitsprecision of 7 digits
�� double double ((±±5.05.0 ×× 1010−324−324 to to ±±1.71.7 ×× 1010308308): 64): 64--bits, bits,
precision of 15precision of 15--16 digits16 digits
�� The default value of floatingThe default value of floating--point types:point types:
�� Is Is 0.0F0.0F for the for the floatfloat typetype
�� Is Is 0.0D0.0D for the for the doubledouble typetype
15
PI Precision PI Precision –– ExampleExample
�� See below the See below the difference in precision when using difference in precision when using
floatfloatand 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}", floatPI);Console.WriteLine("Float PI is: {0}", floatPI);
Console.WriteLine("Double PI is: {0}", doublePI);Console.WriteLine("Double PI is: {0}", doublePI);
16
Abnormalities Abnormalities in the in the FloatingFloating--Point CalculationsPoint Calculations
�� Sometimes abnormalities Sometimes abnormalities can be observed can be observed when using floatingwhen using floating--point numberspoint numbers
�� Comparing floatingComparing floating--point numbers can not be point numbers can not be
performed directly performed directly with with the the ==== operatoroperator
�� 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} equal={2}",Console.WriteLine("a+b={0} sum={1} equal={2}",
a+b, sum, equal);a+b, sum, equal);
17
Decimal FloatingDecimal Floating--Point Point TypesTypes
�� There is a special There is a special decimal floatingdecimal floating--pointpointreal real number number type in C#:type in C#:
�� decimaldecimal ((±±1,01,0 ×× 1010--2828 to to ±±7,97,9 ×× 10102828): 128): 128--bits, bits,
precision of 28precision of 28--29 digits29 digits
�� Used for financial Used for financial calculationscalculations
�� No roundNo round--off off errorserrors
�� 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 numbers)is the suffix for decimal numbers)
18
10/3/2011
4
FloatingFloating--Point and Decimal Point and Decimal FloatingFloating--Point TypesPoint Types
Example 02Example 02--03;0203;02--0404
Boolean TypeBoolean Type
The Boolean Data TypeThe Boolean Data Type
�� The The Boolean Boolean data typedata type::
�� Is declared Is declared by by the the boolbool keywordkeyword
�� Has two possible valuesHas 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
Boolean Values Boolean Values –– ExampleExample
�� Example of boolean Example of boolean variables variables taking taking values of values of truetrueor or falsefalse::
int a = 1;int a = 1;
int b = 2;int b = 2;
bool bool greaterAB = (a > b);greaterAB = (a > b);
Console.WriteLine(greaterAB); // FalseConsole.WriteLine(greaterAB); // False
bool bool equalA1 = (a == 1);equalA1 = (a == 1);
Console.WriteLine(equalA1); // TrueConsole.WriteLine(equalA1); // True
22
Boolean TypeBoolean TypeExample 02Example 02--05; 0205; 02--0606
Character TypeCharacter Type
10/3/2011
5
The Character Data TypeThe Character Data Type
�� The The character data typecharacter data type::
�� Represents symbolic informationRepresents symbolic information
�� Is declared by the Is declared by the charchar keywordkeyword
�� Gives each symbol a corresponding integer codeGives each symbol a corresponding integer code
�� Has a Has a ''\\0'0' default valuedefault value
�� Takes 16 bits of memory (from Takes 16 bits of memory (from U+0000U+0000 to to
U+FFFFU+FFFF))
25
Characters Characters and and CodesCodes
�� The example below shows that every The example below shows that every symbol symbol has an has an its unique Unicode codeits unique Unicode code::
char symbol = 'a';char symbol = 'a';
Console.WriteLine("The code of '{0}' is: {1}",Console.WriteLine("The code of '{0}' is: {1}",
symbol, (symbol, (intint) symbol) symbol););
symbol symbol = = 'b';'b';
Console.WriteLine("The code of '{0}' is: {1}",Console.WriteLine("The code of '{0}' is: {1}",
symbol, (symbol, (intint) symbol);) symbol);
symbol symbol = = 'A';'A';
Console.WriteLine("The code of '{0}' is: {1}",Console.WriteLine("The code of '{0}' is: {1}",
symbol, (symbol, (intint) symbol) symbol););
26
Character TypeCharacter TypeExample 02Example 02--0707
String TypeString Type
The String Data TypeThe String Data Type
�� The The string data typestring data type::
�� Represents a sequence of charactersRepresents a sequence of characters
�� Is declared by the Is declared by the stringstring keywordkeyword
�� 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 Strings can be concatenatedconcatenated
�� Using the Using the ++ operatoroperator
string string s s = = "Microsoft .NET Framework";"Microsoft .NET Framework";
29
Saying Saying Hello Hello –– ExampleExample
�� Concatenating Concatenating the two names of a person to the two names of a person to obtain obtain his full name:his full name:
�� NOTE: a space is missing between the two NOTE: a space is missing between the two
names! We have to add it manuallynames! We have to add it manually
string firstName = "Ivan";string firstName = "Ivan";
string lastName = "Ivanov";string lastName = "Ivanov";
Console.WriteLine("Hello, {0Console.WriteLine("Hello, {0}!}!\\n", n", firstName);firstName);
string fullName = firstName + string fullName = firstName + " " + lastName" " + lastName;;
Console.WriteLine("Your full name is {0Console.WriteLine("Your full name is {0}.",}.",
fullNamefullName););
30
10/3/2011
6
String TypeString TypeExample 02Example 02--08;0208;02--0909
Object TypeObject Type
The Object TypeThe Object Type
�� The object type:The object type:
�� Is declared by the Is declared by the objectobject keywordkeyword
�� Is the Is the base type base type of all other typesof all other types
�� Can Can hold values of any typehold values of any type
33
Using ObjectsUsing Objects
�� Example Example of an object variable taking different of an object variable taking different types of data:types of data:
object dataContainer = 5;object dataContainer = 5;
Console.Write("The value of dataContainer Console.Write("The value of dataContainer is: ");is: ");
Console.WriteLine(dataContainer);Console.WriteLine(dataContainer);
dataContainer = "Five";dataContainer = "Five";
Console.Write("Console.Write("The value of dataContainer The value of dataContainer is: ");is: ");
Console.WriteLine(dataContainer);Console.WriteLine(dataContainer);
34
ObjectsObjectsExample 02Example 02--1010
Introducing VariablesIntroducing Variables
10/3/2011
7
What Is a Variable?What Is a Variable?
�� A variable is a:A variable is a:
�� Placeholder of information that can usually Placeholder of information that can usually be be
changed changed at runat run--timetime
�� 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
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
Declaring And Using Declaring And Using
VariablesVariables
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
IdentifiersIdentifiers
�� Identifiers may consist of:Identifiers may consist of:
�� Letters (Unicode) Letters (Unicode)
�� Digits [0Digits [0--9]9]
�� Underscore "_"Underscore "_"
�� IdentifiersIdentifiers
�� Can begin only with a letter or an underscoreCan begin only with a letter or an underscore
�� Cannot be a C# keywordCannot be a C# keyword
41
Identifiers (2)Identifiers (2)
�� IdentifiersIdentifiers
�� Should Should have a have a descriptive namedescriptive name
�� It is recommended to use only Latin lettersIt is recommended to use only Latin letters
�� Should be neither too long nor too shortShould be neither too long nor too short
�� Note:Note:
�� In C# small In C# small letters are considered different than letters are considered different than
the capital the capital letters (case sensitivity)letters (case sensitivity)
42
10/3/2011
8
Identifiers Identifiers –– ExamplesExamples
�� Examples of Examples of correct identifierscorrect identifiers::
�� Examples of incorrect identifiers:Examples of incorrect identifiers:
int new;int new; // new // new is a keywordis a keyword
int int 2Pac;2Pac; // Cannot // Cannot begin with a digitbegin with a digit
int New = 2int New = 2; // Here ; // Here N is capitalN is capital
int _int _2Pac; // This 2Pac; // This identifiers begins with _identifiers begins with _
string string üşrtüşrt = "Hello"; = "Hello"; // Unicode // Unicode symbols usedsymbols used
// The // The following is more appropriate:following is more appropriate:
string greeting = "Hello"; string greeting = "Hello";
int int n = 100n = 100; // Undescriptive; // Undescriptive
int numberOfClients = 100int numberOfClients = 100; // Descriptive; // Descriptive
// Overdescriptive // Overdescriptive identifier:identifier:
int numberOfPrivateClientOfTheFirm = 100;int numberOfPrivateClientOfTheFirm = 100;
43
Assigning Values Assigning Values
To VariablesTo Variables
Assigning ValuesAssigning Values
�� Assigning of Assigning of values values to to variablesvariables
�� Is achieved by the Is achieved by the == operatoroperator
�� The The == operator hasoperator has
�� Variable identifier on the leftVariable identifier on the left
�� Value of the corresponding data type on the Value of the corresponding data type on the
rightright
�� Could be used in a cascade calling, where Could be used in a cascade calling, where
assigning is done from right to leftassigning is done from right to left
45
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 // Using an already an already declared declared variable:variable:
secondValue = firstValue;secondValue = firstValue;
// The // The following cascade calling assignsfollowing cascade calling assigns
// 3 // 3 to firstValue and then firstValueto firstValue and then firstValue
// to // to thirdValue, so both variables havethirdValue, so both variables have
// the // the value 3 as a resultvalue 3 as a result::
thirdValue = firstValue = 3thirdValue = firstValue = 3; // Avoid this!; // Avoid this!
46
Initializing VariablesInitializing Variables
�� InitializingInitializing
�� Is assigning of initial valueIs assigning of initial value
�� Must be done before the variable is used!Must be done before the variable is used!
�� Several ways of initializing:Several ways of initializing:
�� By using the By using the newnew keywordkeyword
�� By using a literal expressionBy using a literal expression
�� By referring to an already initialized variableBy referring to an already initialized variable
47
Initialization Initialization –– ExamplesExamples
�� Example Example of some initializations:of some initializations:
// The // The following would assign the defaultfollowing would assign the default
// value // value of the int type to num:of the int type to num:
int num = new intint num = new int(); // num = 0(); // num = 0
// This // This is how we use a literal expression:is how we use a literal expression:
float heightInMeters = 1.74f;float heightInMeters = 1.74f;
// Here // Here we use an already initialized variable:we use an already initialized variable:
string greeting = "Hello World!";string greeting = "Hello World!";
string message = greeting;string message = greeting;
48
10/3/2011
9
LiteralsLiterals
What What are Literals?are Literals?
�� Literals are:Literals are:
�� Representations Representations of of values in the source codevalues in the source code
�� There are six types of literalsThere are six types of literals
�� BooleanBoolean
�� IntegerInteger
�� RealReal
�� CharacterCharacter
�� StringString
�� The The nullnull literalliteral50
Boolean and Integer LiteralsBoolean and Integer Literals
�� 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
51
Integer LiteralsInteger Literals
�� Examples of integer literalsExamples of integer literals
�� The The ''0x0x'' and and ''0X0X'' prefixes prefixes mean a mean a
hexadecimal value, e.g. hexadecimal value, e.g. 0xA8F10xA8F1
�� The The ''uu'' and and ''UU'' suffixes suffixes mean a mean a ulongulongor or uintuint
type, e.g. type, e.g. 12345678U12345678U
�� The The ''ll'' and and ''LL'' suffixes suffixes mean a mean a longlong or or ulongulong
type, e.g. type, e.g. 9876543L9876543L
52
Integer Literals Integer Literals –– ExampleExample
�� Note: the letter ‘Note: the letter ‘ll’ is easily confused with the ’ is easily confused with the digit ‘digit ‘11’ so it’s better to use ‘’ so it’s better to use ‘LL’!!!’!!!
// The // The following following variables arevariables are
// initialized // initialized with the same value:with the same value:
int numberInHex = int numberInHex = --0x10;0x10;
int numberInDec = int numberInDec = --16;16;
// The // The following causes an error,following causes an error,
because 234u is of type uintbecause 234u is of type uint
int unsignedInt = 234u;int unsignedInt = 234u;
// The // The following causes an error,following causes an error,
because 234L is of type longbecause 234L is of type long
int longInt = 234L;int longInt = 234L;
53
Real LiteralsReal Literals
�� The real literals:The real literals:
�� Are used for values of type Are used for values of type floatfloat, , doubledoubleand and
decimaldecimal
�� May consist of digits, a sign and May consist of digits, a sign and ““..””
�� May be in exponential May be in exponential notation: 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 The default interpretation is default interpretation is doubledouble54
10/3/2011
10
Real Literals Real Literals –– ExampleExample
�� Example of incorrect Example of incorrect floatfloat literal:literal:
�� A correct way to assign floatingA correct way to assign floating--point value point value (using also the exponential format):(using also the exponential format):
55
// The // The following causes an errorfollowing causes an error
// because // because 12.5 is double by default12.5 is double by default
float realNumber = 12.5;float realNumber = 12.5;
// The // The following is the correctfollowing is the correct
// way // way of assigning the value:of assigning the value:
float realNumber = 12.5f;float realNumber = 12.5f;
// This // This is the same value in exponential format:is the same value in exponential format:
realNumber = realNumber = 1.25e+7f;1.25e+7f;
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 surrounding the Consist of two single quotes surrounding the
character valuecharacter value: : ''<value><value>''
�� The value may be:The value may be:
�� SymbolSymbol
�� The code of the symbolThe code of the symbol
�� Escaping Escaping sequencesequence
56
Escaping SequencesEscaping Sequences
�� Escaping Escaping sequences are:sequences are:
�� Means of presenting a symbol that is usually Means of presenting a symbol that is usually
interpreted otherwise (like interpreted otherwise (like ''))
�� Means of presenting system symbols (like the Means of presenting system symbols (like the
new line symbol)new line symbol)
�� Common Common escaping escaping sequences are:sequences are:
�� \\'' for single for single quotequote \\"" for double quotefor double quote
�� \\\\ for for backslashbackslash \\nn for new for new lineline
�� \\uXXXXuXXXX for denoting any other Unicode symbolfor denoting any other Unicode symbol
57
Character Literals Character Literals –– ExampleExample
�� Examples of different character literals:Examples of different character literals:
char symbol = 'a'; // An ordinary symbolchar symbol = 'a'; // An ordinary symbol
symbol = 'symbol = '\\u006F'; // Unicode symbol code in u006F'; // Unicode symbol code in
// a hexadecimal format// a hexadecimal format
symbol = 'symbol = '\\u8449'; // u8449'; // 葉葉葉葉葉葉葉葉 ((Leaf in Traditional Chinese)Leaf in Traditional Chinese)
symbol = 'symbol = '\\''; // Assigning the single quote symbol''; // Assigning the single quote symbol
symbol = 'symbol = '\\\\'; // Assigning the backslash symbol'; // Assigning the backslash symbol
symbol = 'symbol = '\\n'; // Assigning new line symboln'; // Assigning new line symbol
symbol = 'symbol = '\\t'; // Assigning TAB symbolt'; // Assigning TAB symbol
symbol = "a"; // Incorrect: use single quotessymbol = "a"; // Incorrect: use single quotes
58
String LiteralsString Literals
�� String literals:String literals:
�� Are used for values of the string typeAre used for values of the string type
�� Consist of two double quotes surrounding the Consist of two double quotes surrounding the
value: value: ""<value><value>""
�� May have a May have a @@ prefix which prefix which ignores the ignores the used used
escaping sequences: escaping sequences: @@"<value>""<value>"
�� The value is a sequence of character literalsThe value is a sequence of character literals
string s = "I am a sting literal";string s = "I am a sting literal";
59
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 // Here is a string literal using escape sequencesis a string literal using escape sequences
string quotation = "string quotation = "\\"Hello, Jude"Hello, Jude\\", he said.";", he said.";
string path = "C:string path = "C:\\\\WINNTWINNT\\\\DartsDarts\\\\Darts.exe";Darts.exe";
// Here // Here is an example of the usage of @is an example of the usage of @
quotation = @"""Hello, Jimmy!"", she answered.";quotation = @"""Hello, Jimmy!"", she answered.";
path = @"C:path = @"C:\\WINNTWINNT\\DartsDarts\\Darts.exeDarts.exe";";
string str = @"somestring str = @"some
text";text";
60
10/3/2011
11
String LiteralsString LiteralsExample 02Example 02--1111
Nullable TypesNullable Types
62
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 range type can represent the normal range of values for its underlying value type, plus an of values for its underlying value type, plus an additional additional nullnull valuevalue
�� Useful when dealing with Useful when dealing with DatabasesDatabasesor other or other structures that have default value structures that have default value nullnull
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.WriteLineConsole.WriteLine(("This "This is the integer is the integer with with value value 5 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::
Nullable TypesNullable TypesExample 02Example 02--1212
65
Questions?Questions?
Primitive Data Primitive Data Types and VariablesTypes and Variables
10/3/2011
12
ExercisesExercises
1.1. Declare five variables choosing for each of them the Declare five variables choosing for each of them the
most appropriate of the types most appropriate of the types bytebyte, , sbytesbyte, , shortshort, ,
ushortushort, , intint, , uintuint, , longlong, , ulongulong to represent the to represent the
following values: 52130, following values: 52130, --115, 4825932, 97, 115, 4825932, 97, --10000.10000.
2.2. Which of the following values can be assigned to a Which of the following values can be assigned to a
variable of type variable of type floatfloatand which to a variable of and which to a variable of
type type doubledouble: 34.567839023, 12.345, 8923.1234857, : 34.567839023, 12.345, 8923.1234857,
3456.091?3456.091?
3.3. Write a program that Write a program that safely safely compares compares floatingfloating--point point
numbers with precision of numbers with precision of 0.0000010.000001..
67
Exercises (2)Exercises (2)
4.4. Declare an integer variable and assign it with the Declare an integer variable and assign it with the
value value 254 254 in hexadecimal in hexadecimal format. Use Windows format. Use Windows
Calculator to find its hexadecimal representation.Calculator to find its hexadecimal representation.
5.5. Declare a character variable and assign it with the Declare a character variable and assign it with the
symbol symbol that has Unicode code 72. Hint: first use the that has Unicode code 72. Hint: first use the
Windows Calculator to find the hexadecimal Windows Calculator to find the hexadecimal
representation of 72.representation of 72.
6.6. Declare a boolean variable called Declare a boolean variable called isFemaleisFemaleand and
assign an appropriate value corresponding to your assign an appropriate value corresponding to your
gender.gender.
68
Exercises (3)Exercises (3)
7.7. Declare two Declare two stringstringvariables and assign them with variables and assign them with
“Hello” and “World”. Declare an “Hello” and “World”. Declare an objectobjectvariable and variable and
assign it with the concatenation of the first two assign it with the concatenation of the first two
variables (mind adding an interval). variables (mind adding an interval). Declare a third Declare a third
stringstringvariable and initialize it with the value of the variable and initialize it with the value of the
object object variable (you variable (you should perform type casting).should perform type casting).
8.8. Declare two Declare two stringstringvariables and assign them with variables and assign them with
following value:following value:
Do the above in two different Do the above in two different ways: with and ways: with and
without using quoted strings.without using quoted strings.
The "use" of quotations causes difficulties. The "use" of quotations causes difficulties.
69
Exercises (4)Exercises (4)
9.9. Write a program thatWrite a program that prints an isosceles triangle of prints an isosceles triangle of 9 9 copyright symbols copyright symbols ©©. Use Windows Character . Use Windows Character Map to find the Unicode code of the Map to find the Unicode 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 following employees. Each record would have the following characteristics characteristics –– first name, family name,first name, family name, age,age,gender (m or f), ID number,gender (m or f), ID number, unique employee unique employee number (27560000 to 27569999). Declare the number (27560000 to 27569999). Declare the variables needed to keep the information for a variables needed to keep the information for a single employee using appropriate data typessingle employee using appropriate data types andanddescriptive namesdescriptive names..
11.11. Declare two integer variables and assign them with Declare two integer variables and assign them with 5 and 10 and after that exchange their values.5 and 10 and after that exchange their values.
70