Top Banner
Visual C# 3.0 Application Design
1149
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

Visual C# 3.0 Application Design

FunctionX Press

C# 3.0 Practical Learning

2

INDEX1 - INTRODUCTION TO C#.................................................................................15 INTRODUCTION.....................................................................................................15 C# is a Sharp C...........................................................................................15 Console Applications..................................................................................15 WRITING CODE....................................................................................................17 Practical Learning: Creating a Program......................................................17 Comments..................................................................................................17 Practical Learning: Creating Comments......................................................17 Code Colors................................................................................................18 Indentation ...............................................................................................19 SOLUTION AND PROJECT MANAGEMENT..........................................................................19 A Project ...................................................................................................19 Saving a Project ........................................................................................20 A Solution...................................................................................................20 Executing a Project....................................................................................22 Practical Learning: Executing an Application..............................................23 Adding a Project ........................................................................................23 2 - INTRODUCTION TO VARIABLES...................................................................26 VARIABLES..........................................................................................................26 Practical Learning: Introducing Variables..................................................26 Names in C#...............................................................................................26 Values and Variables on the Console..........................................................28 THE NUMERIC SYSTEMS...........................................................................................28 The Binary System.....................................................................................29 The Decimal System...................................................................................29 The Hexadecimal System...........................................................................30 Signed and Unsigned..................................................................................31 Data Types.................................................................................................31 REPRESENTING NUMBERS.........................................................................................33 A Bit...........................................................................................................33 The Four-Bit Combination...........................................................................33 A BYTE.............................................................................................................36 Characters..................................................................................................38 Escape Sequences......................................................................................38 The Byte Data Type....................................................................................39 Practical Learning: Using Bytes..................................................................41 Signed Byte................................................................................................42 A WORD...........................................................................................................42 Short Integers............................................................................................43 Unsigned Short Integers............................................................................44 Practical Learning: Using Unsigned Short Integers....................................45 3 USING VARIABLES......................................................................................47 A DOUBLE-WORD.................................................................................................47 Practical Learning: Using Unsigned Integers..............................................49 Signed Integers..........................................................................................50 Unsigned Integers......................................................................................51 Practical Learning: Using Unsigned Integers..............................................52 A QUAD-WORD...................................................................................................53 Long Integers.............................................................................................54 Unsigned Long Integers.............................................................................56 REAL NUMBERS....................................................................................................56 Floating-Point Numbers.............................................................................57 Double-Precision Numbers.........................................................................57 Practical Learning: Using a Double-Precision Variable...............................59 Decimal......................................................................................................60

C# 3.0 Practical Learning

3

Practical Learning: Using Decimal Values...................................................63 ACCESSORY DATA TYPES..........................................................................................64 Strings.......................................................................................................64 Practical Learning: Using Strings...............................................................65 Dates and Times.........................................................................................67 Objects.......................................................................................................67 CONSTANTS.........................................................................................................69 Custom Constants......................................................................................69 Built-in Constants.......................................................................................71 4 - INTRODUCTION TO CLASSES.......................................................................73 FUNDAMENTALS OF CLASSES......................................................................................73 Practical Learning: Introducing Classes.....................................................73 Creating a Class.........................................................................................73 Practical Learning: Introducing Classes.....................................................75 Visually Managing Classes..........................................................................75 Declaring a Variable of a Class Type...........................................................76 Sharing a Class...........................................................................................78 Garbage Collection.....................................................................................78 CLASS' FIELDS.....................................................................................................79 Practical Learning: Introducing Class Members..........................................79 ACCESSING CLASS MEMBERS.....................................................................................81 Private Members........................................................................................81 Internal Members.......................................................................................82 INITIALIZING AN OBJECT..........................................................................................82 Practical Learning: Using a Class' Fields.....................................................84 Using an Anonymous Type.........................................................................85 THE METHODS OF A CLASS.......................................................................................86 The Solution Explorer.................................................................................88 Practical Learning: Creating the Methods of a Class...................................89 Accessing a Method....................................................................................91 THE STATIC MEMBERS OF A CLASS..............................................................................92 Static Fields................................................................................................92 Static Methods...........................................................................................96 Static Classes.............................................................................................97 CHARACTERISTICS OF MEMBERS OF A CLASS....................................................................98 Constants...................................................................................................98 this Instance..............................................................................................98 Practical Learning: Using this.....................................................................99 5 - C# AND CODE ORGANIZATION...................................................................101 NAMESPACES......................................................................................................101 Practical Learning: Creating a Namespacep> ..........................................101 Accessing Members of a Namespace........................................................102 Namespace Nesting..................................................................................103 THE SYSTEM NAMESPACE.......................................................................................104 Using a Namespace..................................................................................105 Practical Learning: Using the Keyword.....................................................105 .NET SUPPORT OF DATA TYPES...............................................................................105 C# LANGUAGE ACCESSORIES...................................................................................106 Command Line Options.............................................................................106 Unsafe Code.............................................................................................107 Code Editor Region Delimiter...................................................................109 6 - DATA READING AND FORMATTING............................................................114 DATA READING..................................................................................................114 Practical Learning: Introducing Data Reading..........................................114 String Value Request ...............................................................................114 Practical Learning: Reading String Values................................................115

C# 3.0 Practical Learning

4

Number Request.......................................................................................116 Practical Learning: Reading Numeric Values............................................117 Requesting Dates and Times....................................................................119 Practical Learning: Requesting Date and Time Values..............................120 FORMATTING DATA DISPLAY....................................................................................123 Practical Learning: Displaying Data With Placeholders.............................124 Conversion To String................................................................................126 Practical Learning: Converting to String...................................................127 Number Formatting..................................................................................127 Practical Learning: Formatting Data Display............................................129 Line Formatting........................................................................................132 Data and Time Formatting........................................................................132 Practical Learning: Controlling Date/Time Formatting.............................133 DETAILS ON THE METHODS OF A CLASS..........................................................136 METHODS AND LOCAL VARIABLES..............................................................................136 Practical Learning: Using a Method's Local Variables...............................136 A Method that Returns a Value ................................................................138 Practical Learning: Returning a Value From a Method .............................139 The Main Method of an Application...........................................................140 METHODS' ARGUMENTS..........................................................................................141 Practical Learning: Passing Arguments....................................................142 TECHNIQUES OF PASSING ARGUMENTS.........................................................................144 Passing an Argument by Value.................................................................144 Passing an Argument by Reference..........................................................144 Practical Learning: Passing Arguments By Reference...............................147 Method Overloading.................................................................................148 Practical Learning: Overloading a Method................................................149 CLASS CONSTRUCTION AND DESTRUCTION.....................................................................153 Method Initializer.....................................................................................153 Default Constructor..................................................................................156 The Constructor Initializer.......................................................................157 Constructor Overloading..........................................................................158 The Destructor of a Class.........................................................................160 COMBINATIONS OF CLASSES..........................................................................162 CLASSES COMBINATIONS........................................................................................162 Class Nesting............................................................................................162 A Class as a Field......................................................................................166 Practical Learning: Using a Class as a Field..............................................167 RETURNING A CLASS OR PASSING A CLASS...................................................................169 Returning a Class From a Method.............................................................169 Passing a Class as Argument....................................................................170 Practical Learning: Return a Class or Passing One as Argument...............173 INVOLVING A CLASS AND ITS OWN METHODS................................................................176 Passing a Class as its Own Argument.......................................................176 Returning a Class From its Own Method...................................................180 INTRODUCTION TO CONDITIONS....................................................................184 BOOLEAN VARIABLES............................................................................................184 Practical Learning: Introducing Boolean Variables...................................184 Declaring a Boolean Variable....................................................................188 Retrieving the Value of a Boolean Variable...............................................190 Creating a Boolean Field...........................................................................190 Boolean Arguments..................................................................................192 ENUMERATIONS...................................................................................................192 Declaring an Enumeration Variable..........................................................194 Initializing an Enumeration Variable........................................................194 Enumerations Visibility............................................................................196

C# 3.0 Practical Learning

5

An Enumeration as a Member Variable.....................................................196 Practical Learning: Creating and Using Enumerations..............................198 LOGICAL OPERATORS............................................................................................202 The Equality Operator ==.........................................................................203 The Logical Not Operator !........................................................................204 The Inequality Operator !=......................................................................205 The Comparison for a Lower Value =...................................................208 LOGICALLY INCREMENTING OR DECREMENTING A VALUE.....................................................209 Incrementing a Variable...........................................................................209 Pre and Post-Increment...........................................................................211 Decrementing a Value..............................................................................212 Pre Decrementing a Value........................................................................214 Techniques of Incrementing and Decrementing a Variable......................215 CONDITIONAL STATEMENTS...........................................................................218 CONDITION IS TRUE.......................................................................................218 Practical Learning: Introducing Conditional Expressions..........................218 if..............................................................................................................219 Practical Learning: Using the Simple if Condition.....................................224 ifelse.....................................................................................................226 Practical Learning: Using the if...else Condition.......................................228 LOGICAL CONJUNCTION: AND.................................................................................231 Combining Conjunctions...........................................................................238 LOGICAL DISJUNCTION: OR....................................................................................241 Combinations of Disjunctions...................................................................245IF A

CONDITIONAL SWITCHES...............................................................................246 SWITCHES.....................................................................................................246 The Ternary Operator (?:)........................................................................246 Practical Learning: Introducing Conditional Switches..............................247 ifelse if and ifelse ifelse...................................................................248 CASE SWITCHES..................................................................................................251 Practical Learning: Using Conditional Switches........................................256 Combining Cases......................................................................................260 Using Enumerations.................................................................................262IF

COUNTING AND LOOPING...............................................................................264 CONDITIONAL LOOPING.........................................................................................264 while a Condition is True..........................................................................264 do This while a Condition is True..............................................................265 Practical Learning: Introducing Counting and Looping.............................267 for............................................................................................................273 CONTROLLING THE CONDITIONAL STATEMENTS................................................................274 Nesting a Conditional Statement..............................................................274 Practical Learning: Nesting Conditions.....................................................276 Breaking the Flow of a Conditional Statement..........................................281 Continuing a Conditional Statement.........................................................282 Going to a Designated Label.....................................................................283 Conditional Return...................................................................................283 RECURSION.......................................................................................................285 Creating a Recursive Methods..................................................................286 Using Recursive Methods.........................................................................287 THE PROPERTIES OF A CLASS.........................................................................289 OVERVIEW OF PROPERTIES......................................................................................289 Accessories for Properties........................................................................289 Practical Learning: Introducing Properties...............................................290

C# 3.0 Practical Learning

6

TYPES OF PROPERTIES...........................................................................................291 Property Readers.....................................................................................291 Practical Learning: Creating Property Readers.........................................294 Property Writers......................................................................................297 Read/Write Properties.............................................................................299 Practical Learning: Creating Property Writers..........................................299 A Boolean Property..................................................................................302 PROPERTIES OF EXTERNAL CLASSES............................................................................303 Properties and Enumerations...................................................................303 Practical Learning: Creating an Enumeration Property.............................303 A Class as a Property................................................................................306 Practical Learning: Creating a Property of a Class Type...........................307 INHERITANCE.................................................................................................313 INTRODUCTION TO INHERITANCE...............................................................................313 Practical Learning: Introducing Inheritance.............................................313 Class Derivation.......................................................................................319 Practical Learning: Inheriting...................................................................324 Implementation of Derived Members ......................................................330 The new Modifier......................................................................................334 POLYMORPHISM AND ABSTRACTION..............................................................336 CHARACTERISTICS OF INHERITANCE............................................................................336 Namespaces and Inheritance...................................................................336 Practical Learning: Using Inheritance With Namespaces..........................338 Protected Members..................................................................................339 Virtual Members.......................................................................................341 Practical Learning: Using Virtual Members...............................................342 Abstract Classes.......................................................................................345 Practical Learning: Creating an Abstract Class.........................................345 Abstract Properties and Methods.............................................................346 Practical Learning: Creating an Abstract Property....................................346 Sealed Classes..........................................................................................349 INTERFACES.......................................................................................................350 Practical Learning: Introducing Interfaces...............................................350 The Members of an Interface...................................................................350 Practical Learning: Creating Members of an Interface..............................351 AN INTERFACE AS A BASE CLASS..............................................................................352 Practical Learning: Inheriting From an Interface.....................................352 Implementation of Derived Classes of an Interface..................................353 Practical Learning: Implementing Derived Members of an Interface........356 Class Partial Implementation...................................................................360 Practical Learning: Partially Implementing a Class..................................365 DELEGATES AND EVENTS.................................................................................371 FUNDAMENTALS OF DELEGATES.................................................................................371 Practical Learning: Introducing Delegates...............................................371 Creating a Delegate..................................................................................376 ACCESSING A DELEGATE.........................................................................................377 A Static Method for a Delegate.................................................................378 An Anonymous Delegate..........................................................................379 The Lambda Operator...............................................................................380 A Delegate that Returns a Value...............................................................381 Delegates Compositions...........................................................................382 DELEGATES AND ARGUMENTS...................................................................................382 Using an Argumentative Delegate............................................................383 A Lambda Expression...............................................................................384 A Delegate With Many Arguments............................................................386 Practical Learning: Passing Arguments to a Delegate..............................387

C# 3.0 Practical Learning

7

A Delegate Passed as Argument...............................................................391 DELEGATES AND CLASSES.......................................................................................394 A Delegate that Returns an Object...........................................................395 A Delegate that Takes an Object as Argument.........................................397 EVENTS............................................................................................................398 Event Creation..........................................................................................399 STRUCTURES...................................................................................................402 FUNDAMENTALS OF STRUCTURES................................................................................402 Structure Declaration...............................................................................403 TECHNIQUES OF USING STRUCTURES...........................................................................404 A Structure as a Property.........................................................................404 Returning a Structure From a Method......................................................406 Passing a Structure as Argument.............................................................407 BUILT-IN STRUCTURES: THE INTEGRAL DATA TYPES.......................................................411 Conversion to a String..............................................................................411 Parsing a String........................................................................................411 The Minimum and Maximum Values of a Primitive Type...........................414 Value Comparisons...................................................................................417 BUILT-IN STRUCTURES: THE BOOLEAN TYPE.................................................................420 Parsing a Boolean Variable.......................................................................420 Comparisons of Boolean Variables...........................................................422 FLOATING-POINT NUMBERS....................................................................................424 Operations on Floating-Point Numbers.....................................................425 Comparison Operations............................................................................426 BUILT-IN CLASSES..........................................................................................428 THE OBJECT CLASS..............................................................................................428 Practical Learning: Introducing Ancestor Classes.....................................428 Equality of Two Class Variables................................................................430 Practical Learning: Implementing Equality...............................................431 Stringing a Class......................................................................................432 Practical Learning: Converting to String...................................................433 Boxing and Un-Boxing..............................................................................435 Finalizing a Variable.................................................................................437 Other Built-In Classes..............................................................................437 RANDOM NUMBERS...............................................................................................437 Getting a Random Number.......................................................................437 The Seed of a Random Number................................................................439 Generating Random Numbers in a Range of Numbers..............................440 BUILT-IN ASSEMBLIES AND LIBRARIES........................................................................442 Microsoft Visual Basic Functions..............................................................442 C# CUSTOM LIBRARIES.........................................................................................443 Creating a Library.....................................................................................443 Practical Learning: Creating a Library......................................................444 A LIBRARY CREATED IN ANOTHER LANGUAGE................................................................447 Using a Visual C++/CLI Library................................................................447 Creating a Library.....................................................................................447 Using the Library......................................................................................448 Using the Win32 Library...........................................................................449 INTRODUCTION TO EXCEPTION HANDLING....................................................450 INTRODUCTION TO EXCEPTIONS.................................................................................450 Overview..................................................................................................450 Practical Learning: Introducing Exception Handling.................................451 Exceptional Behaviors..............................................................................454 Practical Learning: Introducing Vague Exceptions...................................456 Exceptions and Custom Messages............................................................457 Practical Learning: Displaying Custom Messages.....................................458

C# 3.0 Practical Learning

8

EXCEPTIONS IN THE .NET FRAMEWORK.......................................................................460 The Exception Class..................................................................................460 The Exception's Message..........................................................................461 Custom Error Messages............................................................................462 A REVIEW OF .NET EXCEPTION CLASSES....................................................................463 The FormatException Exception...............................................................464 Practical Learning: Using the FormatException Class...............................465 The OverflowException Exception............................................................469 The ArgumentOutOfRangeException Exception........................................469 The DivideByZeroException Exception......................................................470 USING EXCEPTION HANDLING........................................................................472 TECHNIQUES OF USING EXCEPTIONS...........................................................................472 Practical Learning: Using Exceptions........................................................472 Throwing an Exception.............................................................................481 Practical Learning: Throwing an Exception...............................................482 Catching Various Exceptions....................................................................485 Practical Learning: Catching Various Exceptions......................................488 Exception Nesting....................................................................................495 Exceptions and Methods...........................................................................497 CUSTOM EXCEPTIONS............................................................................................502 Creating an Exceptional Class..................................................................502 INTRODUCTION TO ARRAYS............................................................................506 A SERIES OF SIMILAR ITEMS..................................................................................506 Practical Learning: Introducing Arrays.....................................................507 Array Creation..........................................................................................507 Practical Learning: Creating an Array.......................................................508 Introduction to Initializing an Array.........................................................508 Practical Learning: Initializing Some Arrays.............................................510 Other Techniques of Initializing an Array.................................................511 ACCESSING THE MEMBERS OF AN ARRAY......................................................................513 Practical Learning: Using the Members of an Array..................................514 For an Indexed Member of the Array........................................................515 Practical Learning: Using a for Loop.........................................................518 For Each Member in the Array..................................................................520 ANONYMOUS ARRAYS............................................................................................521 Creating an Anonymous Array..................................................................521 Accessing the Members of an Anonymous Array......................................523 SELECTING A VALUE FROM AN ARRAY.........................................................................525 Using for and foreach...............................................................................525 Practical Learning: Checking a Value From an Array................................526 ARRAYS AND CLASSES....................................................................................529 AN ARRAY OF A PRIMITIVE TYPE AS A FIELD................................................................529 Practical Learning: Introducing Arrays and Classes.................................530 Presenting the Array................................................................................531 Practical Learning: Presenting an Array...................................................532 ARRAYS AND METHODS..........................................................................................533 An Array Passed as Argument..................................................................534 Returning an Array From a Method..........................................................536 MAIN()'S ARGUMENT...........................................................................................538 Command Request from Main()................................................................539 AN ARRAY OF OBJECTS.........................................................................................541 Practical Learning: Introducing Arrays of Objects....................................542 Creating an Array of Objects....................................................................543 Initializing an Array of Objects.................................................................544 Accessing the Members of the Array........................................................546 Practical Learning: Using an Array of Objects..........................................548

C# 3.0 Practical Learning

9

A CLASS ARRAY AS A FIELD...................................................................................550 Using the Array........................................................................................551 ARRAYS OF OBJECTS AND METHODS...........................................................................554 Passing an Array of Objects as Argument.................................................554 Returning an Array of Objects..................................................................555 Practical Learning: Using Array of Objects With Methods.........................557 ARRAYS AND DELEGATES........................................................................................559 An Array of Delegates..............................................................................560 MULTIDIMENSIONAL ARRAYS.........................................................................562 FUNDAMENTALS OF MULTIDIMENSIONAL ARRAYS.............................................................562 Practical Learning: Introducing Multidimensional Arrays.........................562 Creating a Two-Dimensional Array...........................................................563 Practical Learning: Creating a Two-Dimensional Array.............................565 Accessing the Members of a Two-Dimensional Array...............................566 Practical Learning: Accessing the Members..............................................569 MULTIDIMENSIONAL ARRAYS....................................................................................571 Creating a Multidimensional Array...........................................................571 Initializing a Multidimensional Array........................................................572 Access to Members of a Multidimensional Array.......................................572 MULTIDIMENSIONAL ARRAYS AND CLASSES...................................................................577 A Multidimensional Array as Argument....................................................579 Returning a Multi-Dimensional Array.......................................................580 A MULTIDIMENSIONAL ARRAY OF OBJECTS...................................................................582 A Variable of a Multidimensional Array of Objects....................................582 Accessing the Members of a Multidimensional Array of Objects...............585 MULTIDIMENSIONAL ARRAYS OF OBJECTS AND CLASSES.....................................................586 Passing a Multidimensional Array of Objects............................................588 Returning a Multidimensional Array of Objects........................................589 INTRODUCTION TO JAGGED ARRAYS............................................................................591 Practical Learning: Introducing Jagged Arrays.........................................591 Initialization of a Jagged Array................................................................592 Practical Learning: Initializing a Jagged Array.........................................593 Access to Members of a Jagged Array......................................................595 Practical Learning: Using a Jagged Array.................................................597 THE ARRAY CLASS...........................................................................................601 INTRODUCTION TO THE ARRAY CLASS..........................................................................601 Overview..................................................................................................601 The Length of an Array.............................................................................602 The Rank of an Array................................................................................603 FUNDAMENTAL OPERATIONS ON AN ARRAY....................................................................603 Adding Items to an Array.........................................................................603 Accessing the Members of an Array..........................................................604 MULTIDIMENSIONAL ARRAYS....................................................................................605 Two-Dimensional Arrays..........................................................................606 Three-Dimensional Arrays........................................................................608 Multidimensional Arrays...........................................................................613 ARRANGING THE LIST...........................................................................................614 Arranging the Items in Alphabetical or Numerical Order..........................614 Reversing the Arrangement.....................................................................615 LOCATING AN ELEMENT IN AN ARRAY..........................................................................615 Locating the Index of an Element.............................................................615 The Bounds of an Array............................................................................616 STRINGS.........................................................................................................618 THE CHARACTERS OF A STRING................................................................................618 Practical Learning: Introducing Strings....................................................619 The String: An Array of Characters ..........................................................628

C# 3.0 Practical Learning

10

Converting Characters to the Opposite Case............................................629 Replacing a Character..............................................................................631 WORKING WITH STRINGS......................................................................................632 The Length of a String..............................................................................632 Practical Learning: Using Characters of a String......................................633 Replacing a Sub-String.............................................................................637 Formatting a String..................................................................................637 Copying a String.......................................................................................638 OPERATIONS ON STRINGS.......................................................................................639 String Concatenation................................................................................639 STRINGS COMPARISONS.........................................................................................641 String Equality..........................................................................................642 WORKING WITH SUB-STRINGS................................................................................643 Sub-String Creation..................................................................................643 INTRODUCTION TO INDEXERS........................................................................644 A PROPERTY CAN BE INDEXED................................................................................644 Practical Learning: Introducing Indexed Properties.................................645 An Indexer...............................................................................................649 Indexed Properties of Other Primitive Types............................................650 Using a Non-Integer-Based Index............................................................652 Practical Learning: Creating an Indexer...................................................655 TOPICS ON INDEXED PROPERTIES..............................................................................657 Multi-Parameterized Indexed Properties..................................................657 Overloading an Indexed Property.............................................................661 READ/WRITE INDEXED PROPERTIES..........................................................................664 A Read/Write Property of a Primitive Type..............................................665 CLASSES AND INDEXERS.................................................................................668 FUNDAMENTALS OF INDEXED PROPERTIES AND CLASSES.....................................................668 Practical Learning: Introducing Indexers and Classes..............................668 An Integer-Based Indexed Property.........................................................672 Practical Learning: Using an Integer-Based Indexer................................675 An Indexed Property Using Another Primitive Type.................................676 TOPICS ON INDEXED PROPERTIES AND CLASSES..............................................................680 A Class as Index.......................................................................................680 Overloading a Class-Based Indexed Property...........................................684 Practical Learning: Overloading an Indexer.............................................693 Read/Write Indexed Properties...............................................................694 INTRODUCTION TO COLLECTIONS..................................................................697 ARRAY-BASED LISTS............................................................................................697 Setting Up a Collection.............................................................................697 The Number of Items in a Collection........................................................698 ROUTINE OPERATIONS ON AN ARRAY-BASED LIST...........................................................700 Adding an Item........................................................................................700 Getting an Item From a List.....................................................................701 Inserting an Item in the List....................................................................703 Removing an Item From the List..............................................................706 A COLLECTION OF ITEMS........................................................................................709 Practical Learning: Introducing Collections..............................................709 Implementing a Collection.......................................................................716 Practical Learning: Creating a Class Collection.........................................718 The Beginning of a Collection...................................................................718 Linking the Items of a Collection..............................................................719 Practical Learning: Creating a List's Monitor............................................720 OPERATIONS ON A COLLECTION.................................................................................721 Adding an Item........................................................................................721 Practical Learning: Adding Items to a Collection......................................722

C# 3.0 Practical Learning

11

Retrieving an Item...................................................................................723 Practical Learning: Retrieving the Items of a Collection...........................724 Removing an Item....................................................................................727 Practical Learning: Retrieving the Items of a Collection...........................728 Locating an Item......................................................................................732 ITERATING THROUGH A COLLECTION.............................................................736 ENUMERATING THE MEMBERS OF A COLLECTION..............................................................736 Introduction to System Collections..........................................................736 Practical Learning: Introducing Built-In Collections.................................736 Introduction to the IEnumerator Interface..............................................739 Practical Learning: Introducing Enumerations.........................................740 The Current Item of an Enumeration........................................................741 Practical Learning: Getting to the Current Item.......................................741 Resetting the Tag of the Current Item......................................................742 Practical Learning: Resetting the Tag of the Current Item.......................743 Moving to the Next Item in the Enumerator.............................................744 Practical Learning: Moving to the Next Item in the Enumerator...............745 AN ENUMERABLE COLLECTION..................................................................................746 Getting the Enumerator............................................................................746 Practical Learning: Getting the Enumerator.............................................747 Using foreach...........................................................................................748 Practical Learning: Using foreach on an Enumerator................................750 INTRODUCTION TO BUILT-IN COLLECTION CLASSES......................................753 OVERVIEW OF .NET COLLECTIONS............................................................................753 The ICollection Interface..........................................................................753 Introduction to the ArrayList Class...........................................................753 Practical Learning: Introducing the ArrayList Class..................................753 The Capacity of a List...............................................................................757 A Read-Only List.......................................................................................758 Item Addition...........................................................................................758 Practical Learning: Adding Items to an ArrayList List...............................759 The Number of Items in the List...............................................................771 Item Retrieval..........................................................................................771 Practical Learning: Retrieving Items From an ArrayList List.....................772 Item Location...........................................................................................794 Item Deletion...........................................................................................795 GENERICS.......................................................................................................796 GENERIC METHODS..............................................................................................796 Practical Learning: Introducing Generics.................................................797 Generic Method Creation..........................................................................800 Practical Learning: Creating a Generic Method.........................................800 Calling a Generic Method..........................................................................801 Practical Learning: Calling a Generic Method............................................802 A GENERIC METHOD WITH VARIOUS PARAMETERS..........................................................803 Practical Learning: Using a Method With Various Parameters..................804 A Generic Method With Various Parameter Types.....................................805 Calling a Generic Method With Various Parameter Types.........................806 GENERIC CLASSES...............................................................................................807 Practical Learning: Introducing Generic Classes......................................808 Using a Generic Class...............................................................................810 Passing a Parameter Type to a Method.....................................................812 Returning a Parameter Type.....................................................................812 Practical Learning: Returning a Parameter Type......................................813 A Property of the Parameter Type............................................................815 A GENERIC CLASS WITH MULTIPLE PARAMETERS...........................................................816 Using Multiple Type Parameters...............................................................816

C# 3.0 Practical Learning

12

A Class as a Parameter Type....................................................................818 GENERIC CLASSES AND INHERITANCE..........................................................................820 Generic Classes and Interfaces................................................................825 Constraining a Generic Class....................................................................826 INTRODUCTION TO FILE PROCESSING............................................................831 OVERVIEW OF FILE PROCESSING AND DEFINITIONS..........................................................831 Files.........................................................................................................831 Streams....................................................................................................831 STREAMING PREREQUISITES.....................................................................................832 Practical Learning: Introducing Streaming...............................................832 The Name of a File....................................................................................838 Practical Learning: Specifying the Name of a File.....................................839 The Path to a File.....................................................................................840 THE .NET SUPPORT FOR FILES...............................................................................842 File Existence...........................................................................................842 Practical Learning: Checking the Existence of a File.................................842 File Creation.............................................................................................844 Access to a File.........................................................................................845 File Sharing..............................................................................................845 The Mode of a File....................................................................................845 FUNDAMENTALS OF FILE STREAMING...........................................................................846 Practical Learning: Creating a Stream......................................................847 Stream Writing.........................................................................................848 Stream Closing.........................................................................................849 Practical Learning: Writing to a Stream....................................................849 Stream Reading........................................................................................852 Practical Learning: Reading From a Stream..............................................854 DETAILS ON FILE PROCESSING.......................................................................864 EXCEPTION HANDLING IN FILE PROCESSING..................................................................864 Finally......................................................................................................864 Practical Learning: Finally Releasing Resources.......................................866 .NET Framework Exception Handling for File Processing..........................876 Practical Learning: Handling File Processing Exceptions..........................878 FILE INFORMATION..............................................................................................886 Practical Learning: Introducing File Information......................................886 File Initialization......................................................................................889 File Creation.............................................................................................889 File Existence...........................................................................................890 Writing to a File........................................................................................891 Practical Learning: Writing to a File.........................................................891 Appending to a File...................................................................................892 Practical Learning: Appending to a File....................................................892 FILES OPERATIONS.........................................................................................895 ROUTINE OPERATIONS ON FILES...............................................................................895 Opening a File..........................................................................................895 Deleting a File..........................................................................................895 Copying a File...........................................................................................895 Moving a File............................................................................................896 CHARACTERISTICS OF A FILE....................................................................................897 The Date and Time a File Was Created ....................................................897 The Date and Time a File Was Last Accessed ...........................................898 The Name of a File....................................................................................898 The Extension of a File.............................................................................898 The Size of a File......................................................................................899 The Path to a File.....................................................................................900 The Attributes of a File.............................................................................900

C# 3.0 Practical Learning

13

DIRECTORIES.....................................................................................................900 Practical Learning: Introducing Directories..............................................901 Directory Creation....................................................................................902 Checking for a Directory Existence...........................................................903 Locating a File..........................................................................................903 Practical Learning: Using Directories and Files.........................................903 SERIALIZATION..............................................................................................916 OBJECT SERIALIZATION AND DE-SERIALIZATION.............................................................916 Practical Learning: Introducing Serialization...........................................919 Serialization.............................................................................................922 Practical Learning: Serializing an Object..................................................924 De-Serialization........................................................................................936 Practical Learning: De-Serializing an Object.............................................938 SOAP SERIALIZATION.........................................................................................941 Practical Learning: Introducing SOAP Serialization..................................941 Serialization With SOAP...........................................................................943 Practical Learning: Serializing With SOAP................................................945 De-Serialization With SOAP......................................................................947 Practical Learning: Deserializing With SOAP............................................948 DETAILS ON SERIALIZATION....................................................................................951 Partial Serialization..................................................................................951 Implementing a Custom Serialized Class..................................................954 .NET Built-In Serialized Classes................................................................954

C# 3.0 Practical Learning

14

1 - Introduction to C#IntroductionC# is a Sharp CC#, pronounced c sharp, is a computer language used to give instructions that tell the computer what to do, how to do it, and when to do it. This is a universal language that is used on many operating systems, including Microsoft Windows. C# is one of the languages used in the Microsoft .NET Framework. The Microsoft .NET Framework is a library of objects that create or draw things on the computer.

Console ApplicationsThe C# language is used to create applications that display on a black window referred to as the DOS prompt or DOS window. Those are the types of applications we will create in our lessons. To study the C# language, we will use Microsoft Visual C# 2008 Express Edition or Microsoft Visual C# 2008 Professional. To get Microsoft Visual C# 2008 Express Edition, you can download it free from the Microsoft web site. After downloading it, you can install it. To launch Microsoft Visual C# 2008 Express Edition, you can click Start -> (All) Programs -> Microsoft Visual C# 2008 Expression Edition:

To launch Microsoft Visual C# 2008 Professional, you can click Start -> (All) Programs -> Microsoft Visual Studio 2008. To create the type of applications we will study in our lessons, on the main menu, you can click File -> New Project... In the Templates section of the New Project dialog box, you can click Console Application, accept the default name or change it:

After clicking OK, a skeleton code would be created for you. Right now, we will not review every part of the code. Everything will be introduced and explained as we move on. C# 3.0 Practical Learning16

Writing CodeIntroductionThe programs we will write are meant to give instructions to the computer about what to do, when to do something, and how to do it. You write these instructions in an easy to understand English format, using words we will study. This means that a regular instruction uses normal text with alphabetic characters, numbers, and non-readable symbols. Normally, you can write your instructions using any text editor such as Notepad, WordPad, WordPerfect, or Microsoft Word, etc. When writing your instructions, there are rules your must follow and suggestions you should observe. We sill study each one of them as we move on. The group of instructions used by your program is also referred to as code. To assist you with writing code, Microsoft Visual C# 2008 includes a text editor referred to as the Code Editor. This is the window that displays when you have just created a console application. Besides the Code Editor, the integrated development interface (IDE) of the Microsoft Visual C# 2008 is made of various parts, which we will review when necessary.

Practical Learning: Creating a Program1. Start Microsoft Visual C# 2008 Express Edition or Microsoft Visual C# 2008 Professional 2. To create a new application, on the Start Page, on the right side of Create, click Project 3. In the Templates section, click Console Application 4. Change the Name to GeorgetownCleaningServices1 and click OK

CommentsA comment is a line or paragraph of text that will not be considered as part of your code of a program. There are two types of comments recognized by C#. To display a comment on a line of text, start the line with two forward slashes //. Anything on the right side of // would be ignored. Here is an example:// This line will be ignored. I can write in it anything I want

The above type of comment is used on only one line. You can also start a comment with /*. This type of comment ends with */. Anything between this combination of /* and */ would not be read. Therefore, you can use this technique to span a comment on more than one line.

Practical Learning: Creating Comments

C# 3.0 Practical Learning

17

1. To create comments, change the file as follows:using System; // using System.Collections.Generic; // using System.Linq; // using System.Text; /* namespace GeorgetownCleaningServices1 {*/ class Program { static void Main(/* string[] args */) { } } //}

2. To save the project, on the Standard toolbar, click the Save All button

3. Accept the name as GeorgetownCleaningServices1 and click Save

Code ColorsCode is written in a wide area with a white background. This is the area you use the keyboard to insert code with common readable characters. The Code Editor uses some colors to differentiate categories of words or lines of text. The colors used are highly customizable. To change the colors, on the main menu, you can click Tools -> Options... In the Options dialog box, in the Environment section, click Fonts and Colors. To set the color of a category, in the Display Items section, click the category. In the Item Foreground combo box, select the desired color. If you want the words of the category to have a colored background, click the arrow of the Item Background combo box and select one:

C# 3.0 Practical Learning

18

In both cases, the combo boxes display a fixed list of colors. If you want more colors, you can click a Custom button to display the Color dialog box that allows you to "create" a color.

IndentationIndentation is another feature that makes your program easy to read. Indentation is a technique of grouping lines of code by category. To delimit the items of your code, you should indent them by two empty spaces or one tab. Indentation should be incremental. That is, when a line of code appears to be a child of the previous line, the new line should be indented.

Solution and Project ManagementA ProjectWe have seen how to create a console application. Microsoft Visual C# allows you to create various other types of applications. This is why you should first display the New Project dialog box to select your option. Besides console applications, in future lessons, we will start some applications with the Empty Project. We will also learn how to create a library using the Class Library option. We will ignore the other three options in this book. To control the indentation of your code, on the main menu, click Tools -> Options... In the left list, expand C#, followed by Formatting and click Indentation. Then change the options on the right side:

C# 3.0 Practical Learning

19

After making the changes, click OK to validate or Cancel to ignore.

Saving a ProjectIn previous versions of Microsoft Visual C# (namely 2002 and 2003), you always had to formally create a project in order to use one and you always had to save it. After realizing that many of the projects that developers or students create are for experimental purposes, Microsoft provided the ability to only temporarily create a project, then to save it or not. Saving a project allows you to keep on a medium so you can refer to it later. When Microsoft Visual Studio 2008 (any edition) is installed, it creates a folder named Visual Studio 2008 in your My Documents folder. The My Documents folder is called your personal drive or your personal directory. Inside of the Visual Studio 2008 folder, it creates a sub-folder named Projects. By default, this is where it would save your projects, each with its own folder. To save a project, on the Standard toolbar, you can click the Save All button . Alternatively, on the main menu, you can click File -> Save All. If the project had already been saved but you want to save it under a different name, on the main menu, you can click File -> Save project name As...

A SolutionA solution is used to coordinate the different aspects of an application that is being created. When you create a project, it represents one detail of the application you have in mind. Besides the code you are writing, you may want to add other items. Instead of one project, in the next sections, we will see that a solution can contain more than one project. When creating a project, the solution holds the same name as the project. You can see their names in the Solution Explorer: 20 C# 3.0 Practical Learning

The solution and a project can have different names. While working on a project, to rename the solution, in the Solution Explorer, you can click the first node, which is the name of the solution starting with Solution. Then, in the Properties window, click (Name) and type the name of your choice:

This name is temporary, especially if you have not yet saved the project. If you want to permanently save a solution for later use, there are two techniques you can use. If you start saving a project for the first time, it would bring the Save Project dialog box. By default, Microsoft Visual Studio selects your personal directory as the path to the solution. This is called the location. In the location, Microsoft Visual Studio creates a folder as the solution of the project. The solution must have, or must be stored, in its own folder. As mentioned earlier, Microsoft Visual Studio uses the name of the project as the name of the solution. To rename the solution, you can change the string in the Solution Name text box. Remember that you can enter the name of the project in the Name text box. Here is an example:

C# 3.0 Practical Learning

21

When you save a project (for the first time), by default, Microsoft Visual C# creates a new folder for it in the My Documents\Visual Studio 2008\Projects folder. It uses the name of the solution to name the folder. It creates some files and stores them in that new folder. Then, it creates a sub-folder, using the name of the project, inside of the folder of the solution. Besides the sub-folder with the name as the project, it creates another folder named debug. It also creates another folder named Debug in the sub-folder of the name of the project. In each folder and some other folders, it creates some files that we will not pay attention to for now. If the project had already been saved but you want to change the name of the solution, on the main menu, you can click File -> Save solution-name.sln As... This would bring the Save File As dialog box where you can specify the name of the solution and click Save.

Executing a ProjectAfter creating a project and writing code, you may want to see the result. To do this, you must execute the application. This would create an executable that you can use on other computers and that you can distribute to other people. To execute an application, on the main menu, you can click Debug -> Start Without Debugging. Instead of going through the main menu every time, you can add the Start Without Debugging button to a toolbar. To do this, you can right-click any toolbar and click Customize... In the Commands property page of the Customize dialog box, you can click Debug in the Categories click, then drag Start Without Debugging, and drop it on a toolbar. Here is an example:

C# 3.0 Practical Learning

22

After adding the button(s), you can click Close. The next time you want to execute an application, you can just click this button.

Practical Learning: Executing an Application1. To execute the application, on the main menu, click Debug -> Start Without Debugging 2. After viewing the result in a DOS window, press Enter to close it

Adding a ProjectOne of the most valuable features of Microsoft Visual Studio 2005 is that it allows you to work on more than one project without launching more than one instance of the studio. This means that you can add a project to another project you are working on and treat each as a separate entity.

C# 3.0 Practical Learning

23

Before adding one project to another, you must save, or you must have saved, the current project. To add a project, in the Solution Explorer, you can rightclick the most top node (it starts with Solution) and position the mouse on Add:

If you have a project that was previously saved but you don't want to open a separate instance of Microsoft Visual Studio for it, you can click Existing Project... This would bring the Add Existing Project dialog box that allows you to select a project from a folder. To add a new project, after right-clicking, you can click New Project... If you add a new project, and if you want to keep it for future references, you must save it. To save the new project, you can click the Save All button on the Standard toolbar. After saving the new project, a folder with its name would be created inside of the folder of the solution. On the right side of the name of the solution in Solution, the number of its projects is specified in parentheses, as 1 project, or 2 projects, etc. After adding a project, each would be represented by its own node in the Solution Explorer and in the Class View. Here is an example:

C# 3.0 Practical Learning

24

Also, a sub-folder for each project is created in the folder of the solution:

In the Solution, the name of one of the projects, if there is more than one, is in bold characters. This project is called the StartUp Project. If, on the main menu, you click Debug -> Start Without Debugging, the project in bold characters would be executed. If you want to change the start up project, you can rightclick its node and click Set As StartUp Project.

C# 3.0 Practical Learning

25

2 - INTRODUCTION TO VARIABLESVariablesDefinitionA computer receives information from different applications in various forms. Sometimes a person types it using the keyboard. Sometimes the user clicks the mouse. Sometimes information comes from another, more complicated source. The idea is that the computer spends a great deal of its time with various pieces of information. Information provided to the computer through a program is called datum and the plural is data. Sometimes the word data is used both for singular and plural items.

Data used by the computer comes and goes regularly as this information changes. For this reason, such information is called a variable. When the user enters data in a program, the computer receives it and must store it somewhere to eventually make it available to the program as needed. For a program used to process employment applications, the types of information a user would enter into the program are the name, the residence, the desired salary, years of experience, education level, etc. Because there can be so much information for the same program, you must specify to the computer what information you are referring to and when. To do this, each category of piece of information must have a name.

Practical Learning: Introducing Variables1. Start Microsoft Visual C# 2008 Express Edition or Microsoft Visual C# 2008 Professional From now on, we will only refer to Microsoft Visual C# 2. To create a new application, on the Start Page, on the right side of Create, click Project 3. In the Templates section, click Console Application 4. Change the Name to GeorgetownCleaningServices2 and click OK

Names in C#C# 3.0 Practical Learning26

To name the variables of your program, you must follow strict rules. In fact, everything else in your program must have a name. C# uses a series of words, called keywords, for its internal use. This means that you must avoid naming your objects using one of these keywords. They are:abstract const

extern

int interface internal

out override

short

typeofuint

asbase bool break byte case catch char

continue false decimal default finally

sizeof

paramsprivate

stackalloc ulongstatic

fixed

is locklong namespace new null object

uncheckedunsafe ushort using virtual void

delegate float do double else enum for foreach goto if

protected string public readonly ref return sbyte sealed struct switch this throw true try

checked eventclass

implicitin

volatilewhile

explicit

operator

Besides these keywords, C# has other words that should be reserved only depending on how and where they are used. These are referred to as contextual keywords and they are:get partial set value where

yield

Once you avoid these words, there are rules you must follow when naming your objects. On this site, here are the rules we will follow:

The name must start with a letter or an underscore After the first letter or underscore, the name can have letters, digits, and/or underscores The name must not have any special characters other than the underscore C# 3.0 Practical Learning27

The name cannot have a space

Besides these rules, you can also create your own but that abide by the above. C# is case-sensitive. This means that the names Case, case, and CASE are completely different. For example, main is always written Main.

Values and Variables on the ConsoleAs mentioned already, the applications we will create display in a dark object called the DOS window. Here is an example showing some values:

To display a value in this window, you can enter it in the parentheses of the Console.Write() or Console.WriteLine(). Here are two examples:using System; class Program { static void Main() { Console.WriteLine(248); Console.Write(1); } }

If you write Console.WriteLine() with empty parentheses, an empty line would be displayed. In future lessons, we will learn what the meanings of Console, Write(), and WriteLine().

The Numeric SystemsIntroductionWhen a computer boots, it loads the operating system. If you want to use a program, you must find it either on the Start menu or from its directory and take the necessary action to open it. Such a program uses numbers, characters, meaningful words, pictures, graphics, etc, that are part of the program. As these things are numerous, so is the size of the program, and so is C# 3.0 Practical Learning28

the length of time needed to come up. Your job as a programmer is to create such programs and make them available to the computer, then to people who want to interact with the machine. To write your programs, you will be using alphabetic letters that are a, b, c, d, e, f, g, h, I, j, k, l, m, n, o, p, q, r, s, t, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z. You will also use numeric symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Additionally, you will use characters that are not easily readable but are part of the common language; they are ` ~ ! @ # $ % ^ & * ( ) _ + - = : < > ; , . /. Some of these symbols are used in the C# language while some others are not. When creating your programs, you will be combining letters and/or symbols to create English words or language instructions. Some of the instructions you will give to the computer could consist of counting the number of oranges, converting water to soup, or making sure that a date occurs after January 15. After typing an instruction, the compiler would translate it to machine language. The computer represents any of your instructions as a group of numbers. Even if you ask the computer to use an orange, it would translate it into a set of numbers. As you give more instructions or create more words, the computer stores them in its memory using a certain amount of space for each instruction or each item you use. There are three numeric systems that will be involved in your programs, with or without your intervention.

The Binary SystemWhen dealing with assignments, the computer considers a piece of information to be true or to be false. To evaluate such a piece, it uses two symbols: 0 and 1. When a piece of information is true, the computer gives it a value of 1; otherwise, its value is 0. Therefore, the system that the computer recognizes and uses is made of two symbols: 0 and 1. As the information in your computer is greater than a simple piece, the computer combines 0s and 1s to produce all sorts of numbers. Examples of such numbers are 1, 100, 1011, or 1101111011. Therefore, because this technique uses only two symbols, it is called the binary system. When reading a binary number such as 1101, you should not pronounce "One Thousand One Hundred And 1", because such a reading is not accurate. Instead, you should pronounce 1 as One and 0 as zero or o. 1101 should be pronounced One One Zero One, or One One o One. The sequence of the symbols of the binary system depends on the number that needs to be represented.

The Decimal SystemThe numeric system that we are familiar with uses ten symbols that are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Each of these symbols is called a digit. Using a combination of these digits, you can display numeric values of any kind, such as 240, 3826 or 234523. This system of representing numeric values is called the decimal system because it is based on 10 digits. C# 3.0 Practical Learning29

When a number starts with 0, a calculator or a computer ignores the 0. Consequently, 0248 is the same as 248; 030426 is the same as 30426. From now on, we will represent a numeric value in the decimal system without starting with 0: this will reduce, if not eliminate, any confusion. Decimal Values: 3849, 279, 917293, 39473 Non- Decimal Values: 0237, 0276382, k2783, R3273 The decimal system is said to use a base 10. This allows you to recognize and be able to read any number. The system works in increments of 0, 10, 100, 1000, 10000, and up. In the decimal system, 0 is 0*100 (= 0*1, which is 0); 1 is 1*100 (=1*1, which is 1); 2 is 2*100 (=2*1, which is 2), and 9 is 9*100 (= 9*1, which is 9). Between 10 and 99, a number is represented by left-digit * 10 1 + right-digit * 100. For example, 32 = 3*101 + 2*100 = 3*10 + 2*1 = 30 + 2 = 32. In the same way, 85 = 8*101 + 5*100 = 8*10 + 5*1 = 80 + 5 = 85. Using the same logic, you can get any number in the decimal system. Examples are: 2751 = 2*103 + 7*102 + 5*101 + 1*100 = 2*1000 + 7*100 + 5*10 + 1 = 2000 + 700 + 50 + 1 = 2751 67048 = 6*104 + 7*103 + 0*102 + 4*101 + 8*100 = 6*10000 + 7*1000+0*100+4*10+8*1 = 67048 Another way you can represent this is by using the following table: Add 0 to the preceding 100000 10000 1000 1000 100 10 0 value 0 0 0

etc

When these numbers get large, they become difficult to read; an example is 279174394327. To make this easier to read, you can separate each thousand fraction with a comma. Our number would become 279,174,394,327. You can do this only on paper, never in a program: the compiler would not understand the comma(s).

The Hexadecimal SystemWhile the decimal system uses 10 digits (they are all numeric), the hexadecimal system uses sixteen (16) symbols to represent a number. Since the family of Latin languages consists of only 10 digits, we cannot make up new ones. To compensate for this, the hexadecimal system uses alphabetic characters. After counting from 0 to 9, the system uses letters until it gets 16 different values. The letters used are a, b, c, d, e, and f, or their uppercase equivalents A, B, C, D, E, and F. The hexadecimal system counts as follows: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, and f; or 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. To produce a hexadecimal number, you use a combination of these sixteen symbols. Examples of hexadecimal numbers are 293, 0, df, a37, c23b34, or ffed54. At first glance, the decimal representation of 8024 and the hexadecimal representation of 8024 are the same. Also, when you see fed, is it a name of a federal agency or a hexadecimal number? Does CAB represent a taxi, a social organization, or a hexadecimal number? C# 3.0 Practical Learning30

From now on, to express the difference between a decimal number and a hexadecimal one, each hexadecimal number will start with 0x or 0X. The number will be followed by a valid hexadecimal combination. The letter can be in uppercase or lowercase. Legal Hexadecimals: 0x273, 0xfeaa, 0Xfe3, 0x35FD, 0x32F4e Non-Hex Numbers: 0686, ffekj, 87fe6y, 312 There is also the octal system but we will not use it anywhere in our applications.

Signed and UnsignedThe numbers we have used so far were counting from 0, then 1, then 2, and up to any number desired, in incrementing values. Such a number that increments from 0, 1, 2, and up is qualified as positive. By convention, you do not need to let the computer or someone else know that such a number is positive: by just displaying or saying it, the number is considered positive. This is the basis of our counting items. In real life, there are numbers counted in decrement values. Such numbers start at 1 and move down to -2, -3, -4 etc. These numbers are qualified as negative. When you write a number normally, such as 42, 502, or 1250, the number is positive. If you want to express the number as negative, you use the on the left side of the number. The symbol is called a sign. Therefore, if the number does not have the symbol, C++ (or the compiler) considers such a number as unsigned. In C++, if you declare a variable that would represent a numeric value and you do not initialize (assign a value to) such a variable, the compiler will consider that the variable can hold either a signed or an unsigned value. If you want to let the compiler know that the variable should hold only a positive value, you will declare such a variable as unsigned.