logo资料库

CSharp基础.pdf

第1页 / 共1122页
第2页 / 共1122页
第3页 / 共1122页
第4页 / 共1122页
第5页 / 共1122页
第6页 / 共1122页
第7页 / 共1122页
第8页 / 共1122页
资料共1122页,剩余部分请下载后查看
Contents
Detailed Table of Contents
Preface
About the Book
Please Excuse Us for the Bugs in the Translation!
Who Is This Book Aimed At?
Previous Knowledge Is Not Required!
What Is the Scope of This Book?
What Will This Book Not Teach You?
How Is the Information Presented?
C# and .NET Framework
The C# Programming Language
The Microsoft .NET Framework
Why C#?
C# or Java?
Why Not PHP?
Why Not C or C++?
Advantages of C#
Examples Are Given in C# 5 and Visual Studio 2012
How То Read This Book?
Do Not Skip the Exercises!
How Much Time Will We Need for This Book?
Exercises: Complex or Easy?
Why Are Data Structures and Algorithms Emphasized?
Job Interviews at Google
Job Interviews at Microsoft
About the LINQ Technology
Do You Really Want to Become a Programmer?
Motivate Yourself to Become a Programmer or Find Another Job!
A Look at the Book’s Contents
Chapter 0: Preface
Chapter 1: Introduction to Programming
Chapter 2: Primitive Types and Variables
Chapter 3: Operators and Expressions
Chapter 4: Console Input and Output
Chapter 5: Conditional Statements
Chapter 6: Loops
Chapter 7: Arrays
Chapter 8: Numeral Systems
Chapter 9: Methods
Chapter 10: Recursion
Chapter 11: Creating and Using Objects
Chapter 12: Exception Handling
Chapter 13: Strings and Text Processing
Chapter 14: Defining Classes
Chapter 15: Text Files
Chapter 16: Linear Data Structures
Chapter 17: Trees and Graphs
Chapter 18: Dictionaries, Hash Tables and Sets
Chapter 19: Data Structures and Algorithm Complexity
Chapter 20: Object-Oriented Programming Principles
Chapter 21: High-Quality Programming Code
Chapter 22: Lambda Expressions and LINQ
Chapter 23: Methodology of Problem Solving
Chapters 24, 25, 26: Sample Programming Exam
Chapters 28: Conclusion
History: How Did This Book Come to Be?
The Origins of This Book
The Java Programming Fundamentals Book
The C# Programming Fundamentals Book
The Translation of the C# Book: from Bulgarian to English
Bulgaria? Bulgarian Authors? Is This True?
Authors and Contributors
The Panel of Authors
Dilyan Dimitrov
Hristo Germanov
Iliyan Murdanliev
Mihail Stoynov
Mihail Valkov
Mira Bivas
Nikolay Kostov
Nikolay Nedyalkov
Nikolay Vasilev
Pavel Donchev
Pavlina Hadjieva
Radoslav Ivanov
Radoslav Kirilov
Radoslav Todorov
Stanislav Zlatinov
Stefan Staev
Svetlin Nakov
Teodor Bozhikov
Teodor Stoev
Tsvyatko Konov
Veselin Georgiev
Veselin Kolev
Yordan Pavlov
Yosif Yosifov
The Java Book Authors
The Editors
The Translators
Other Contributors
The Book Is Free of Charge!
Reviews
Review by Nikola Mihaylov, Microsoft
Review by Vassil Bakalov, Microsoft
Review by Vassil Terziev, Telerik
Review by Veselin Raychev, Google
Review by Vassil Popovski, VMware
Review by Pavlin Dobrev, ProSyst Labs
Review by Nikolay Manchev, Oracle
Review by Panayot Dobrikov, SAP AG
Review by Lyubomir Ivanov, Mobiltel
Review by Hristo Deshev, Entrepreneur
Review by Hristo Radkov, Clever IT (London, UK)
License
Common Definitions
Rights and Limitations of the Users
Rights and Limitations of the Authors
Resources Coming with the Book
The Book’s Website
Discussion Forum
Presentation Slides Coming with the Book
Video Materials for Self-Education with the Book
Interactive Mind Maps
C# Book Fan Club
Chapter 1. Introduction to Programming
In This Chapter
What Does It Mean "To Program"?
How Do Computers Process Information?
Managing the Computer
The Essence of Programming
Stages in Software Development
Gathering the Requirements
Planning and Preparing the Architecture and Design
Implementation
Product Testing
Deployment and Operation
Technical Support
Documentation
Software Development Is More than Just Coding
Our First C# Program
How Does Our First C# Program Work?
Defining a Class
Defining the Main() Method
Contents of the Main() Method
C# Distinguishes between Uppercase and Lowercase!
The Program Code Must Be Correctly Formatted
Main Formatting Rules
File Names Correspond to Class Names
The C# Language and the .NET Platform
The C# Language
Keywords
Automatic Memory Management
Independence from the Environment and the Programming Language
Mono (.NET for Linux)
Microsoft Intermediate Language (MSIL)
Common Language Runtime (CLR) – the Heart of .NET
The .NET Platform
.NET Framework
.NET Technologies
Application Programming Interface (API)
.NET Documentation
What We Need to Program in C#?
.NET Framework
Text Editor
Compilation and Execution of C# Programs
Creating C# Programs in the Windows Console
Compiling C# Programs in Windows
Compiling and Running C# Programs in Windows
Changing the System Paths in Windows
Visual Studio IDE
Integrated Development Environments
What Is Visual Studio?
Creating a New C# Project
Compiling the Source Code
Starting the Project
Debugging the Program
Alternatives to Visual Studio
SharpDevelop
MonoDevelop
Decompiling Code
C# in Linux, iOS and Android
Other .NET Languages
Exercises
Solutions and Guidelines
Chapter 2. Primitive Types and Variables
In This Chapter
What Is a Variable?
Data Types
Characteristics
Types
Correspondence between C# and .NET Types
Integer Types
Integer Types – Example
Real Floating-Point Types
Real Type Float
Special Values of the Real Types
Real Type Double
Real Floating-Point Types – Example
Precision of the Real Types
Accuracy of Real Types – Example
About the Presentation of the Real Types
Errors in Calculations with Real Types
Real Types with Decimal Precision
Boolean Type
Boolean Type – Example
Character Type
Character Type – Example
Strings
Strings – Example
Object Type
Using Objects – Example
Nullable Types
Variables
Characteristics of Variables
Naming Variables – Rules
Naming Variables – Examples
Naming Variables – Recommendations
Declaring Variables
Assigning a Value
Initialization of Variables
Default Variable Values
Value and Reference Types
Value and Reference Types and the Memory
Literals
Types of Literals
Boolean Literals
Boolean Literals – Example
Integer Literals
Integer Literals – Examples
Real Literals
Real Literals – Examples
Character Literals
Escaping Sequences
Escaping Sequences – Examples
String Literals
String Literals – Examples
Exercises
Solutions and Guidelines
Chapter 3. Operators and Expressions
In This Chapter
Operators
What Is an Operator?
Operators in C#
Operator Categories
Types of Operators by Number of Arguments
Operators – Example
Operator Precedence in C#
Arithmetical Operators
Arithmetical Operators – Example
Logical Operators
Logical Operators – Example
Laws of De Morgan
Operator for Concatenation of Strings
Operator for Concatenation of Strings – Example
Bitwise Operators
Bitwise Operators and Their Performance
Bitwise Operators – Example
Comparison Operators
Comparison Operators – Example
Assignment Operators
Assignment Operators – Example
Cascade Assignment
Compound Assignment Operators
Conditional Operator ?:
Conditional Operator "?:" – Example
Other Operators
The "." Operator
Square Brackets [] Operator
Brackets () Operator
Type Conversion Operator
Operator "as"
Operator "new"
Operator "is"
Operator "??"
Other Operators – Examples
Type Conversion and Casting
Implicit Type Conversion
Implicit Type Conversion – Examples
Possible Implicit Conversions
Explicit Type Conversion
Explicit Type Conversion – Example
Data Loss during Type Conversion
Forcing Overflow Exceptions during Casting
Possible Explicit Conversions
Conversion to String
Conversion to String – Example
Expressions
Side Effects of Expressions
Expressions, Data Types and Operator Priorities
Division by Zero
Using Brackets to Make the Code Clear
Exercises
Solutions and Guidelines
Chapter 4. Console Input and Output
In This Chapter
What Is the Console?
Communication between the User and the Program
When to Use the Console?
How to Launch the Console?
More about Consoles
Basic Console Commands
Windows Console Commands
Standard Input-Output
Printing to the Console
Standard Input and Standard Output
Devices for Console Input and Output
Console.Out Stream
Using Console.Write(…) and Console.WriteLine(…)
Concatenation of Strings
Concatenation of Mixed Types
Some Features of String Concatenation
Formatted Output with Write(…) and WriteLine(…)
Formatted Output – Examples
Composite Formatting
Composite Formatting String
Formatting Items
Index Component
Alignment Component
The "formatString" Component
Format String Components for Numbers
Standard Formats for Numbers
Standard Formats for Numbers – Example
Custom Formats for Numbers
Format String Components for Dates
Standard Defined Date Formats
Custom Date Formats
Format String Enumeration Components
Formatting Strings and Localization
Console Input
Reading through Console.ReadLine()
Reading through Console.Read()
Reading Numbers
Parsing Numbers Conditionally
Reading by Console.ReadKey()
Simplified Reading of Numbers through Nakov.IO.Cin
Console Input and Output – Examples
Printing a Letter
Area of a Rectangle or a Triangle
Exercises
Solutions and Guidelines
Chapter 5. Conditional Statements
In This Chapter
Comparison Operators and Boolean Expressions
Comparison Operators
Comparison of Integers and Characters
Comparison of References to Objects
Logical Operators
Logical Operators && and ||
Logical Operators & and |
Logical Operators ^ and !
Conditional Statements "if" and "if-else"
Conditional Statement "if"
Conditional Statement "if" – Example
Conditional Statement "if" and Curly Brackets
Conditional Statement "if-else"
Conditional Statement "if-else" – Example
Nested "if" Statements
Nested "if" Statements – Example
Sequences of "if-else-if-else-…"
Conditional "if" Statements – Good Practices
Conditional Statement "switch-case"
How Does the "switch-case" Statement Work?
Rules for Expressions in Switch
Using Multiple Labels
Good Practices When Using "switch-case"
Exercises
Solutions and Guidelines
Chapter 6. Loops
In This Chapter
What Is a "Loop"?
While Loops
Usage of While Loops
Summing the Numbers from 1 to N
Check If a Number Is Prime – Example
Operator "break"
Calculating Factorial – Example
Do-While Loops
Usage of Do-While Loops
Calculating Factorial – Example
Factorial of a Large Number – Example
Product in the Range [N…M] – Example
For Loops
Initialization of For Loops
Condition of the For Loop
Update of the Loop Variables
The Body of the Loop
For-Loop – Example
Calculating N^M – Example
For-Loop with Several Variables
Operator "continue"
Foreach Loops
Nested Loops
Printing a Triangle – Example
Prime Numbers in an Interval – Example
Lucky Numbers – Example
Lottery 6/49 – Example
Exercises
Solutions and Guidelines
Chapter 7. Arrays
In This Chapter
What Is an "Array"?
Declaration and Allocation of Memory for Arrays
Declaring an Array
Creation of an Array – the Operator "new"
Array Initialization and Default Values
Declaration and Initialization of an Array – Example
Boundaries of an Array
Access to the Elements of an Array
Going Out of Bounds of the Array
Reversing an Array – Example
Reading an Array from the Console
Check for Symmetric Array – Example
Printing an Array to the Console
Iteration through Elements of an Array
Iteration with a For Loop
Iteration with "foreach" Loop
Iteration with "foreach" Loop – Example
Multidimensional Arrays
What Is a Multidimensional Array? What Are Matrices?
Multidimensional Array Declaration and Allocation
Two-Dimensional Array Initialization
Accessing the Elements of a Multidimensional Array
Length of Multidimensional Arrays
Printing Matrices – Example
Reading Matrices from the Console – Example
Maximal Platform in a Matrix – Example
Arrays of Arrays
Declaration and Allocation an Array of Arrays
Memory Allocation
Initialization and Access to the Elements
Pascal’s Triangle – Example
Exercises
Solutions and Guidelines
Chapter 8. Numeral Systems
In This Chapter
History in a Nutshell
Applications of the Sexagesimal Numeral System
Short Summary
Numeral Systems
What Are Numeral Systems?
Positional Numeral Systems
Non-Positional Numeral Systems
Roman Numeral System
Greek Numeral System
The Binary Numeral System – Foundation of Computing Technology
Decimal Numbers
Binary Numbers
Converting From Binary to Decimal Numeral System
Horner Scheme
Converting from Decimal to Binary Numeral System
Operations with Binary Numbers
Bitwise "and"
Bitwise "or"
Bitwise "exclusive or"
Bitwise Negation
Hexadecimal Numbers
Fast Transition from Binary to Hexadecimal Numbers
Numeral Systems – Summary
Representation of Numbers
Representing Integer Numbers in the Memory
Unsigned Integers
Representing Negative Numbers
Integer Types in C#
Big-Endian and Little-Endian Representation
Representing Real Floating-Point Numbers
Representing Floating-Point Numbers – Example
Mantissa Normalization
The Float and Double Types in C#
Errors When Using Floating-Point Numbers
Precision of Floating-Point Numbers
The Decimal Type
Character Data (Strings)
Encoding Schemes (Encodings)
Presenting a Sequence of Characters
Char Type
String Type
Exercises
Solutions and Guidelines
Chapter 9. Methods
In This Chapter
Subroutines in Programming
What Is a "Method"?
Why to Use Methods?
Better Structured Program and More Readable Code
Avoid Duplicated Code
Code Reuse
How to Declare, Implement and Invoke a Method?
Declaring Our Own Method
Where Is Method Declaration Allowed?
Method Declaration
Method Signature
Method Names
Rules to Name a Method
Modifiers
Implementation (Creation) of Own Method
The Body of a Method
Local Variables
Invoking a Method
Who Takes Control over the Program when We Invoke a Method?
Where a Method Can Be Invoked From?
Method Declaration and Method Invocation
Parameters in Methods
Declaring Methods with Parameters
Method to Display a Company Logo – Example
Method to Calculate the Sum of Prices of Books – Example
Method Behavior According to Its Input
Method to Show whether a Number is Positive – Example
Method with Multiple Parameters
Difference in Declaration of Methods with Multiple Parameters
Invoking Methods with Parameters
Difference between Parameters and Arguments of a Method
Passing Arguments of a Primitive Type
Passing Arguments of Reference Type
Passing of Expressions as Method Arguments
Passing of Arguments Compatible with the Parameter Type
Compatibility of the Method Parameter and the Passed Value
Keeping the Declaration Sequence of the Arguments Types
Variable Number of Arguments (var-args)
How to Declare Method with Variable Number of Arguments
Variable Number of Arguments: Arrays vs. "params"
Position and Declaration of a Method with Variable Arguments
Limitations on the Count for the Variable Arguments
Specifics of Empty Parameter List
Method with Variable Number of Arguments – Example
Optional Parameters and Named Arguments
Method Overloading
Method Parameters and Method Signature
Overloaded Methods Invocation
Methods with Coinciding Signatures
Triangles with Different Size – Example
Returning a Result from a Method
Declaring a Method that Returns a Result
How to Use the Returned Value?
Assigning to a Variable
Usage in Expressions
Using the Returned Value as Method Parameter
Returned Value Type
The Operator "return"
Compatibility of the Result and the Retuning Type
Using an Expression after the Return Operator
Features of the Return Operator
Multiple Return Statements
Why Is the Returned Value Type not a Part of the Method Signature?
Fahrenheit to Celsius Conversion – Example
Difference between Two Months – Example
Input Data Validation – Example
Sorting – Example
Best Practices when Using Methods
Exercises
Solutions and Guidelines
Chapter 10. Recursion
In This Chapter
What Is Recursion?
Example of Recursion
Direct and Indirect Recursion
Bottom of Recursion
Creating Recursive Methods
Recursive Calculation of Factorial
Recurrent Definition
Finding a Recurrent Dependence
Algorithm Implementation
Recursion or Iteration?
Simulation of N Nested Loops
Nested Loops – Recursive Version
Nested Loops – Iterative Version
Which is Better: Recursion or Iteration?
Fibonacci Numbers – Inefficient Recursion
Fibonacci Numbers – Efficient Recursion
Fibonacci Numbers – Iterative Solution
More about Recursion and Iteration
Searching for Paths in a Labyrinth – Example
Paths in a Labyrinth – Recursive Algorithm
Paths in a Labyrinth – Implementation
Paths in a Labyrinth – Saving the Paths
Paths in a Labyrinth – Testing the Program
Using Recursion – Conclusions
Exercises
Solutions and Guidelines
Chapter 11. Creating and Using Objects
In This Chapter
Classes and Objects
What Is Object-Oriented Programming?
What Is an Object?
What Is a Class?
Classes, Attributes and Behavior
Objects – Instances of Classes
Classes in C#
What Are Classes in C#?
An Example Class
System Classes
Creating and Using Objects
Creating and Releasing Objects
Creating Objects with Set Parameters
Releasing the Objects
Access to Fields of an Object
Access to the Memory and Properties of an Object – Example
Calling Methods of Objects
Calling Methods of Objects – Example
Constructors
Constructor with Parameters
Calling Constructors – Example
Static Fields and Methods
When to Use Static Fields and Methods?
Static Fields and Methods – Example
Examples of System C# Classes
The System.Environment Class
The System.String Class
The System.Math Class
The System.Math Class – More Examples
The System.Random Class
The System.Random Class – Generating a Random Password
Namespaces
What Are Namespaces in C#?
Defining Namespaces
Nested Namespaces
Full Names of Classes
Inclusion of a Namespace
Using a Namespace – Example
Exercises
Solutions and Guidelines
Chapter 12. Exception Handling
In This Chapter
What Is an Exception?
Exceptions
Catching and Handling Exceptions
Exceptions in the Object-Oriented Programming
Exceptions in .NET
An Example Code Throwing an Exception
How Do Exceptions Work?
Catching Exceptions in C#
The try-catch Programming Construct
Catching Exceptions – Example
Stack Trace
Stack Trace – Example
Reading the Stack Trace
Throwing Exceptions (the throw Construct)
Exceptions Hierarchy
The Exception Class
Exception – Constructors, Methods and Properties
Application vs. System Exceptions
Throwing and Catching Exceptions
Nested Exceptions
How to Read the Stack Trace with Nested Exceptions?
Visualizing Exceptions
Which Exceptions to Handle and Which Not?
Throwing Exceptions from the Main() Method – Example
Catching Exceptions at Different Levels – Example
The try-finally Construct
When Should We Use try-finally?
Resource Cleanup – Defining the Problem
Resource Cleanup – Solving the Problem
Resource Cleanup – Better Solution
Multiple Resources Cleanup
IDisposable and the "using" Statement
IDisposable
The Keyword "using"
Nested "using" Statements
When to Use the "using" Statement?
Advantages of Using Exceptions
Separation of the Exception Handling Code
Error Handling without Exceptions
Error Handling with Exceptions
Grouping Different Error Types
Catching Exceptions at the Most Appropriate Place
Best Practices when Using Exceptions
When to Rely on Exceptions?
Throw Exceptions to the End User?
Throw Exceptions at the Appropriate Level of Abstraction!
If Your Exception Has a Source, Use It!
Give a Detailed Descriptive Error Message!
Error Messages with Wrong Content
Use English for All Exception Messages
Never Ignore the Exceptions You Catch!
Dump the Error Messages in Extreme Cases Only!
Don’t Catch All Exceptions!
Only Catch Exceptions You Know How to Process!
Exercises
Solutions and Guidelines
Chapter 13. Strings and Text Processing
In This Chapter
Strings
What Is a String?
The System.String Class
The String Class: Universal Solution?
Strings are Immutable
Strings and Char Arrays
Strings – Simple Example
Strings Escaping
Declaring a String
Creating and Initializing a String
Setting a String Literal
Assigning Value of Another String
Passing a String Expression
Reading and Printing to the Console
Reading Strings
Printing Strings
Strings Operations
Comparing Strings in Alphabetical Order
Comparison for Equality
Comparing Strings in Alphabetical Order
The == and != Operators
Memory Optimization for Strings (Interning)
Operations for Manipulating Strings
Strings Concatenation
Switching to Uppercase and Lowercase Letters
Searching for a String within Another String
Searching into a String – Example
Searching with IndexOf(…) – Example
Finding All Occurrences of a Substring – Example
Extracting a Portion of a String
Extracting a File Name and File Extension – Example
Splitting the String by a Separator
Splitting Strings by Multiple Separators – Example
How to Remove the Empty Elements after Splitting?
Replacing a Substring
Regular Expressions
Regular Expressions – Example
Explaining the Arguments of Regex.Replace(…)
Removing Unnecessary Characters at the Beginning and at the End of a String
Removing Unnecessary Characters by a Given List
Constructing Strings: the StringBuilder Class
Strings Concatenation in a Loop: Never Do This!
How Does the String Concatenation Works?
Why Concatenating Strings in a Loop is a Bad Practice?
Concatenating in Loop of 200,000 Iterations – Example
Processing Strings in the Memory
Building and Changing Strings with StringBuilder
Reversing a String – Example
How Does the StringBuilder Class Work?
StringBuilder – More Important Methods
Extracting All Capital Letters from a Text – Example
StringBuilder: the Right Solution
String Formatting
The ToString(…) Method
Using of String.Format(…)
Parsing Data
Parsing Numeric Types
Parsing Dates
Exercises
Solutions and Guidelines
Chapter 14. Defining Classes
In This Chapter
Custom Classes
Let’s Recall: What Does It Mean Class and Object?
What Does a Class Contain?
Elements of the Class
Sample Class: Dog
Usage of Class and Objects
How to Use a Class Defined by Us (Custom Class)?
Example – A Dog Meeting
Nature of Objects
Organizing Classes in Files and Namespaces
Organizing Classes in Namespaces
Encoding of Files and Using of Cyrillic and Unicode
Modifiers and Access Levels (Visibility)
Modifiers and Access Levels
Access Level "public"
Access Level "private"
Access Level "internal"
Assembly
Declaring Classes
Class Visibility
Access Level "public"
Access Level "internal"
Access Level "private"
Body of the Class
Class Naming Convention
The Reserved Word "this"
Fields
Declaring Fields in a Class
Scope
Initialization during Declaration
Default Values of the Fields
Automated Initialization of Local Variables and Fields
Custom Default Values
Modifiers "const" and "readonly"
Constants Based on "const"
Constants Based on "readonly"
Methods
Declaring of Class Method
Example – Method Declaration
Accessing Non-Static Data of the Class
Accessing Non-Static Fields from Non-Static Method
Calling Non-Static Methods
Skip "this" Keyword When Accessing Non-Static Data
Hiding Fields with Local Variables
Visibility of Fields and Methods
Access Level "public"
Access Level "internal"
Access Level "private"
How to Decide Which Access Level to Use?
Constructors
What Is a Constructor?
Calling a Constructor
Declaring a Constructor
Constructor’s Name
Parameter List
Modifiers
Visibility of the Constructors
Initialization of the Fields in the Constructor
Fields Initialization in the Constructor
Representation in the Memory
Order of Initialization of the Fields
Declaring a Constructor with Parameters
Scope of Parameters of the Constructor
Constructor with Variable Number of Arguments
Constructor Overloading
Reusing Constructors
Default Constructor
How the Default Constructor Works?
When a Default Constructor Will Not Be Created?
Difference between a Default Constructor and a Constructor without Parameters
Properties
Properties in C# – Introduction by Example
Properties – Encapsulation of Fields
Example of Encapsulation
Physical Presentation of the Properties in a Class
Property without Declaration of a Field
Declaring Properties in C#
The Body of a Property
Method for Reading the Value of a Property (Getter)
Calling a Method for Reading Property’s Value
Method for Modifying Property’s Value (Setter)
Calling a Method for Modifying the Property’s Value
Assertion of the Input Values
Automatic Properties in C#
Types of Properties
Static Classes and Static Members
What the Static Elements Are Used For?
Method to Sum Two Numbers
Instance Counter for Given Class
What Is a Static Member?
Static Fields
Declaration of Static Fields
Initialization during Declaration
Accessing Static Fields
Modification of the Static Field Values
Constants
Compile-Time Constants (const)
Assigning Constant Values at Runtime
Runtime Constants (readonly)
Naming the Constants
Using Constants
Static Methods
Declaration of Static Methods
Accessing Static Methods
Access between Static and Non-Static Members
Accessing Non-Static Members from Non-Static Method
Accessing Static Elements from Non-Static Method
Accessing Static Elements of the Class from Static Method
Accessing Non-Static Elements from Static Method
Unauthorized Access to Non-Static Field – Example
Illegal Call of Non-Static Method from Static Method – Example
Static Properties of the Class
Static Properties and the Keyword “this”
Accessing Static Properties
Static Classes
Static Constructors
Static Constructor – Example
Structures
Structure (struct) – Example
Structures are Value Types
Class or Structure?
Enumerations
Declaration of Enumerations
Nature of Enumerations
Hidden Numerical Value of Constants in Enumeration
Use of Enumerations
Inner Classes (Nested Classes)
Declaration of Inner Classes
Inner Classes – Example
Usage of Inner Classes
Declare Enumeration in a Class
Generics
Shelter for Homeless Animals – Example
What Is a Generic Class?
Declaration of Generic Class
Specifying Generic Classes
Using Unknown Types by Declaring Fields
Using Unknown Types in a Method’s Declaration
Typifying (Generics) – Behind the Scenes
Generic Methods
Features by Declaration of Generic Methods in Generic Classes
Using a Keyword "default" in a Generic Source Code
Advantages and Disadvantages of Generics
Naming the Parameters of the Generic Types
Exercises
Solutions and Guidelines
Chapter 15. Text Files
In This Chapter
Streams
What Is a Stream?
Basic Things You Need to Know about Streams
Basic Operations with Streams
Creation
Reading
Writing
Positioning
Closing
Streams in .NET – Basic Classes
Binary and Text Streams
Binary Streams
Text Streams
Relationship between Text and Binary Streams
Reading from a Text File
StreamReader Class for Reading a Text File
Opening a Text File for Reading
Full and Relative Paths
Universal Relative to Physical Path Resolver
Reading a Text File Line by Line – Example
Automatic Closing of the Stream after Working with It
File Encodings. Reading in Cyrillic
Character Encodings
Reading a Cyrillic Content
The Unicode Standard. Reading in Unicode
Writing to a Text File
The StreamWriter Class
Printing the Numbers [1…20] in a Text File – Example
Input / Output Exception Handling
Intercepting Exceptions when Working with Files
Catching an Exception when Opening a File – Example
Text Files – More Examples
Occurrences of a Substring in a File – Example
Editing a Subtitles File – Example
Exercises
Solutions and Guidelines
Chapter 16. Linear Data Structures
In This Chapter
Abstract Data Structures
What Is a Data Structure?
What Is an Abstract Data Type?
Basic Data Structures in Programming
List Data Structures
List
Abstract Data Structure "List"
Static List (Array-Based Implementation)
Linked List (Dynamic Implementation)
Comparing the Static and the Dynamic Lists
Doubly-Linked List
The ArrayList Class
The ArrayList Class – Example
ArrayList of Numbers – Example
Generic Collections
The List Class
The List Class – Array-Based Implementation
When to Use List?
Prime Numbers in Given Interval – Example
Union and Intersection of Lists – Example
Converting a List to Array and Vice Versa
The LinkedList Class
When Should We Use LinkedList?
Basic Operations in the LinkedList Class
When Should We Use LinkedList?
Stack
The Abstract Data Type "Stack"
Static Stack (Array-Based Implementation)
Linked Stack (Dynamic Implementation)
The Stack Class
The Stack Class – Basic Operations
Stack Usage – Example
Correct Brackets Check – Example
Queue
Abstract Data Type "Queue"
Static Queue (Array-Based Implementation)
Linked Queue (Dynamic Implementation)
The Queue Class
The Queue – Basic Operations
Queue Usage – Example
Sequence N, N+1, 2*N – Example
Exercises
Solutions and Guidelines
Chapter 17. Trees and Graphs
In This Chapter
Tree Data Structures
Trees
Example – Hierarchy of the Participants in a Project
Trees Terminology
Tree Implementation – Example
How Does Our Implementation Work?
Depth-First-Search (DFS) Traversal
Creating a Tree
Traverse the Hard Drive Directories
Recursive DFS Traversal of the Directories
Breadth-First Search (BFS)
Binary Trees
Binary Tree – Example
Binary Tree Traversal
Recursive Traversal of Binary Tree – Example
How Does the Example Work?
Ordered Binary Search Trees
Comparability between Objects
Properties of the Ordered Binary Search Trees
Ordered Binary Search Trees – Example
Ordered Binary Search Trees: Implementation of the Nodes
Comparability between Objects in C#
Ordered Binary Trees – Implementation of the Main Class
Inserting an Element
Searching for an Element
Removing an Element
Balanced Trees
The Hidden Class TreeSet in .NET Framework
Graphs
Graphs – Basic Concepts
Graphs – Presentations
Graphs – Basic Operations
Common Graph Applications
Exercises
Solutions and Guidelines
Chapter 18. Dictionaries, Hash-Tables and Sets
In This Chapter
Dictionary Data Structure
Dictionary Data Structure – Example
The Abstract Data Structure “Dictionary” (Associative Array, Map)
The Interface IDictionary
Implementation of Dictionary with Red-Black Tree
The Class SortedDictionary
Using SortedDictionary Class – Example
IComparable Interface
IComparer Interface
Hash-Tables
Dictionary Implementation with Hash-Table
What is a Hash-Table?
Class Dictionary
Class Dictionary – Main Operations
Students and Marks – Example
Hashing and Hash-Functions
Hash-Functions
The Method GetHashCode() in .NET Framework
Collisions with Hash-Functions
Implementing the Method GetHashCode()
Implementing GetHashCode() – Example
Interface IEqualityComparer
Resolving the Collision Problem
Chaining in a List
Implementation of a Dictionary with Hash-Table and Chaining
Open Addressing Methods for Collision Resolution
Linear Probing
Quadratic Probing
Double Hashing
Cuckoo Hashing
The "Set" Data Structure
The Abstract Data Structure "Set"
Set Implementations in .NET Framework
Implementation with Hash-Table – HashSet
Implementation with Red-Black Tree – SortedSet
Exercises
Solutions and Guidelines
Chapter 19. Data Structures and Algorithm Complexity
In This Chapter
Why Are Data Structures So Important?
Algorithm Complexity
Typical Algorithm Complexities
Complexity and Execution Time
Complexity by Several Variables
Best, Worst and Average Case
Roughly Estimated Complexity
Complexity by Memory
Estimating Complexity – Examples
Comparison between Basic Data Structures
When to Use a Particular Data Structure?
Array (T[])
Singly / Doubly Linked List (LinkedList)
Dynamic Array (List)
Stack
Queue
Dictionary, Implemented with a Hash-Table (Dictionary)
Dictionary, Implemented with a Balanced Tree (SortedDictionary)
Set, Implemented with a Hash-Table (HashSet)
Set, Implemented with a Balanced Tree (SortedSet)
Choosing a Data Structure – Examples
Generating Subsets
Sorting Students
Sorting a Phone Book
Searching in a Phone Book
Choosing a Data Structure – Conclusions
External Libraries with .NET Collections
Power Collections for .NET
C5 Collections for .NET
Exercises
Solutions and Guidelines
Chapter 20. Object-Oriented Programming Principles
In This Chapter
Let’s Review: Classes and Objects
Object-Oriented Programming (OOP)
Fundamental Principles of OOP
Inheritance
How Does Inheritance Work in .NET?
Inheritance of Classes – Example
The "base" Keyword
Constructors with Inheritance
Constructors and the Keyword "base" – Example
Access Modifiers of Class Members and Inheritance
The System.Object Class
.NET, Standard Libraries and Object
The Base Type Object Upcasting and Downcasting – Example
The Object.ToString() Method
Object.ToString() – Example
Overriding ToString() – Example
Virtual Methods: the "override" and "new" Keywords
Transitive Properties of Inheritance
Transitiveness – Example
Inheritance Hierarchy
Class Diagrams
What is UML Class Diagram?
A Class Based on a Class Diagram – Example
Class Diagram – Example of Generalization
Associations
From Diagrams to Classes
Aggregation
Composition
Abstraction
Abstraction – Abstract Data Example
Interfaces
Interfaces – Key Concepts
Interfaces – Example
Abstraction and Interfaces
When Should We Use Abstraction and Interfaces?
When Should We Write Interfaces?
Encapsulation
Encapsulation – Examples
Polymorphism
Abstract Classes
Abstract Class – Examples
Purely Abstract Classes
Virtual Methods
Virtual Methods – Example
Virtual Methods and Methods Hiding
The Difference between Virtual and Non-Virtual Methods
When Should We Use Polymorphism?
Cohesion and Coupling
Cohesion
Strong Cohesion
Strong Cohesion in a Class
Strong Cohesion in a Class – Example
Strong Cohesion in a Method
Weak Cohesion
Weak Cohesion – Example
Best Practices with Cohesion
Coupling
Loose Coupling
Loose Coupling – Example
Tight Coupling
Tight Coupling – Example
Best Practices with Coupling
Spaghetti Code
Cohesion and Coupling in Engineering Disciplines
Object-Oriented Modeling (OOM)
Steps in Object-Oriented Modeling
Identification of Classes
Identification of Class Attributes
Identification of Operations on Classes
Identification of Relationships between Classes
UML Notation
Use Case Diagrams
Use Case Diagrams – Example
Sequence Diagrams
Sequence Diagrams – Example
Messages – Example
Statechart Diagrams
Activity Diagrams
Design Patterns
The Singleton Design Pattern
The Singleton Design Pattern – Example
The Factory Method Design Pattern
The Factory Method Design Pattern – Example
Other Design Patterns
Exercises
Solutions and Guidelines
Chapter 21. High-Quality Programming Code
In This Chapter
Why Is Code Quality Important?
What Does Quality Programming Code Mean?
Characteristics of Quality Code
Why Should We Write Quality Code?
Coding Conventions
Managing Complexity
Identifier Naming
Avoid Abbreviations
Use English
Consistency in Naming
Names of Classes, Interfaces and Other Types
How Long Should Class Names Be?
Naming Interfaces and Other Types
Names of Enumeration Types
Attribute Names
Exception Names
Delegate Names
Naming Namespaces
Assembly Names
Method Names
Methods that Return a Value
Single Purpose of a Method
Cohesion and Naming
How Long Should Method Names Be?
Method Parameters
Property Names
Variable Names
Names of Boolean Identifiers
Named Constants
Naming of Specific Data Types
Naming by Prefixing or Suffixing
Code Formatting
Why Does Code Need Formatting?
Block Formatting
Rules for Formatting a Method
Formatting Multiple Method Declarations
How to Put Parentheses?
Formatting the Parameter List of Methods: Space after Commas
Rules for Formatting of Types
Rules for Ordering the Contents of a Class
Formatting Rules for Loops and Conditional Statements
Usage of Empty Lines
Rules for Moving to the Next Line and Alignment
High-Quality Classes
Software Design
Object-Oriented Programming (OOP)
Abstraction
Inheritance
Encapsulation
Constructors
Deep and Shallow Copy
High-Quality Methods
Why Should We Use Methods?
What Should a Method Do?
Strong Cohesion and Loose Coupling
How Long Should a Method Be?
Method Parameters
Proper Use of Variables
Returning a Result
Principles for Initialization
Partially Initialized Objects
Declaring a Variable within a Block or a Method
Scope, Lifetime and Span of Variables
Minimizing the Variable Scope
Minimizing the Variable Span
Minimizing the Variable Lifetime
Minimizing the Variable Span and Lifetime – Example
Use of Variables – More Rules
Proper Use of Expressions
Use of Constants
When to Use Constants?
When Not to Use Constants?
Proper Use of Control Flow Statements
With or Without Curly Brackets?
Proper Usage of Conditional Statements
Deep Nesting of Conditional Statements
Proper Use of Loops
Choosing an Appropriate Looping Construct
Do Not Nest Too Many Loops
Defensive Programming
Assertions
Assertions vs. Exceptions
Defensive Programming with Exceptions
Code Documentation
Self-Documenting Code
Properties of Self-Documenting Code
Self-Documenting Code – Important Questions
Effective Comments
XML Documentation in C#
Code Refactoring
Refactoring at Data Level
Refactoring at Method and Class Level
Unit Testing
Unit Testing – Example
Benefits of Unit Testing
Benefits of Unit Testing – Example
Unit Testing Frameworks and Tools
Unit Testing with Visual Studio Team Test (VSTT)
Additional Resources
Exercises
Solutions and Guidelines
Chapter 22. Lambda Expressions and LINQ
In This Chapter
Extension Methods
Extension Methods – Examples
Extension Methods for Interfaces
Anonymous Types
Anonymous Types – Example
More about Anonymous Types
Arrays of Anonymous Types
Lambda Expressions
Lambda Expressions – Examples
Using Lambda Expressions with Anonymous Types
Sorting with Lambda Expressions
Statements in Lambda Expressions
Lambda Expressions as Delegates
LINQ Queries
Data Sources with LINQ
Data Filtering with LINQ
Results of LINQ Queries
Sorting Data with LINQ
Grouping Results with LINQ
Joining Data with LINQ
Nested LINQ Queries
LINQ Performance
Exercises
Solutions and Guidelines
Chapter 23. Methodology of Problem Solving
In This Chapter
Basic Principles of Solving Computer Programming Problems
Use Pen and Paper
Generate Ideas and Give Them a Try!
Decompose the Task into Smaller Subtasks
"Cards Shuffle" Problem – Example
First Subtask: a Single Swap
Second Subtask: Choosing a Random Number
Third Subtask: Combining Swaps
Another Example: Sorting Numbers
Verify Your Ideas!
"Cards Shuffle" Problem: Verifying the Idea
Sorting Numbers: Verifying the Idea
If a Problem Occurs, Invent a New Idea!
Choose Appropriate Data Structures!
What Kind of Data Structure Should We Use?
Can We Use an Array?
Can We Use Another Data Structure?
How to Represent the Other Data Objects?
Sorting Numbers: Choosing a Data Structures
Think about the Efficiency!
How to Estimate the Performance of Given Algorithm?
The Efficiency Is a Matter of Compromise
Sorting Numbers: Estimating the Performance
Implement Your Algorithm!
Write the Code Step by Step!
Writing Code Step by Step – Example
Step 1 – Defining the Class "Card"
Testing of the Class "Card"
Step 2 – Creating and Printing a Deck of Cards
Printing the Deck – Testing the Code
Step 3 – Single Swap
Search in Google!
Single Swap – Testing the Code
Single Swap – Correcting the Mistakes
Step 4 – Card Shuffling
Card Shuffling – Testing
Step 5 – Console Input
Sorting Numbers – Step by Step
Test Your Solution!
How to Test?
Testing with Good Examples of the Common Cases
What Else to Test For?
A Hard Common-Case Test
Borderline Cases
Borderline Case: Shuffling One Card
Borderline Case: Shuffling Two Cards
Borderline Case: Shuffling Zero Cards
Regression Testing
Performance Tests
Shuffling Cards – Performance Tests
Sorting Numbers – Performance Tests
General Conclusions
Exercises
Solutions and Guidelines
Chapter 24. Sample Programming Exam – Topic #1
In This Chapter
Problem 1: Extract Text from HTML Document
Inventing an Idea
Checking the Idea
Clarification of the Statement of the Problem
A New Idea for Solving the Problem
Break a Task into Subtasks
What Data Structures to Use?
Consider the Efficiency
Step 1 – Read the Input File
Test the Input File Reading Code
Step 2 – Remove the Tags
Testing the Tag Removal Code
Step 3 – Remove the Empty Lines
Testing the Empty Lines Removal Code
Remove the Empty Lines: Second Attempt
Remove the Empty Lines: Test Again
Step 4 – Print Results in a File
Testing the Solution
Fixing the Leading Spaces Defect
Performance Test
How to Fix the Problem with the Tag at Two Lines?
A New Idea: Processing the Text Char by Char
Implementing the New Idea
Testing the New Solution
Where Is the Problem?
How to Fix the Problem?
Testing the New Solution
Problem 2: Escape from Labyrinth
Figure Out an Idea for a Solution
Verification of the Idea
What Data Structures to Use?
Think About the Efficiency
Think of Another Idea
Check the New Idea
Breaking the Problem into Subproblems
Checking the Performance of the New Algorithm
Check If the New Algorithm Is Correct
What Data Structures to Use?
Step 1 – The Class Cell
Step 2 – Reading the Input File
Testing the Input File Reading Code
Step 3 – Finding the Shortest Path
Checking after Step 3
Step 4 – Writing the Result to a File
Testing the Complete Solution of the Problem
Problem 3: Store for Car Parts
Inventing an Idea for Solution
Checking the Idea
What Data Structures to Use to Describe the Relationship between Two Classes?
Dividing the Task into Subtasks
Implementation: Step by Step
Step 1: The Class Car
Testing the Class Car
Step 2: The Class Manufacturer
Testing the Class Manufacturer
Step 3: The Part Category Enumeration
Step 4: The Class Part
Testing the Class Part
Step 5: The Class Shop
Step 6: The Class TestShop
Testing the Solution
Exercises
Solutions and Guidelines
Chapter 25. Sample Programming Exam – Topic #2
In This Chapter
Problem 1: Counting the Uppercase / Lowercase Words in a Text
Coming Up with an Appropriate Idea for a Solution
Breaking Down the Problem into Subproblems
How Do We Split the Text Up into Separate Words?
How Do We Count the Words?
Verifying the Idea
Let’s Consider the Data Structures
Let’s Consider the Efficiency
Let’s Write Down the Solution
Step 1: Finding the Separators in the Text
Testing the ExtractSeparators(…) Method
Correcting the ExtractSeparators(…) Method
Testing Again after the Fix
Step 2: Splitting Up the Text in Separate Words
Testing the Word Extracting Method
Step 3: Determining Whether a Word Is in Uppercase or Lowercase
Step 4: Counting the Words
Testing the Word Counting Method
Step 5: Console Input
Step 6: Putting All Together
Testing the Solution
A Word on Performance
Problem 2: A Matrix of Prime Numbers
Coming Up with an Appropriate Idea for a Solution
Breaking Down the Problem into Subproblems
Verifying the Idea
Consider the Data Structures
Consider the Efficiency
Step 1: Check to Find If a Number Is a Prime
Testing the Prime Checking Method
Step 2: Finding the Next Prime Number
Testing the Next Prime Number Finder
Step 3: Printing the Matrix
Step 4: Console Input
Testing the Entire Solution
A Word on Performance
Improved Performance: Sieve of Eratosthenes
Problem 3: Evaluate an Arithmetic Expression
Coming Up with an Appropriate Idea for a Solution
Verifying the Idea
Data Structures and Efficiency
Breaking Down the Problem into Subproblems
Step 1: Extracting the Numbers
Testing the Extraction of Numbers
Step 2: Extracting the Operators
Testing the Extraction of Operators
Step 3: Evaluating the Expression
Test the Evaluation of Expression
Step 4: Console Input
Step 5: Putting All Together
Testing the Solution
Small Corrections and Repeated Testing
Performance Test
Exercises
Solutions and Guidelines
Chapter 26. Sample Programming Exam – Topic #3
In This Chapter
Problem 1: Spiral Matrix
Start Thinking on the Problem
Inventing an Idea for the Solution
Checking the Idea
Data Structures and Efficiency
Implementation of the Idea: Step by Step
Implementing the First Few Steps
Performing a Partial Check after the First Few Steps
Assigning the Initial Values
Putting All Together
Testing the Solution
Problem 2: Counting Words in a Text File
Start Thinking on the Problem
Inventing an Idea for a Solution
Checking the Idea
Inventing a Better Idea
Checking the New Ideas
Checking the Line by Line Algorithm
Checking the Char by Char Algorithm
Decompose the Problem into Subproblems
Line by Line Algorithm Decomposed into Subproblems
Char by Char Algorithm Decomposed into Subproblems
Think about the Data Structures
Think about the Performance
Implementation: Step by Step
Line by Line Algorithm: Step by Step Implementation
Testing the Line by Line Algorithm
Char by Char Algorithm: Step by Step Implementation
Testing the Char by Char Algorithm
Testing for Performance
Invent a Better Idea (Again)
Counting Substrings with the Aho-Corasick Algorithm
Problem 3: School
Start Thinking on the Problem
Inventing an Idea for Solution
Checking the Idea
Dividing the Problem into Subproblems
Think about the Data Structures
Implementation: Step by Step
Step 1: Class Student
Testing the Class Student
Step 2: Class Group
Testing the Class Group
Step 3: Class Teacher
Testing the Class Teacher
Step 4: Class School
Step 5: Class SchoolTest
Testing the Solution
Exercises
Solutions and Guidelines
Conclusion
Did You Solve All Problems?
Have You Encountered Difficulties with the Exercises?
How Do You Proceed After Reading the Book?
Free Courses at Telerik Software Academy
Good Luck to Everyone!
Fundamentals of Computer Programming with C# (The Bulgarian C# Programming Book) by Svetlin Nakov & Co. http://www.introprogramming.info ISBN: 978-954-400-773-7 ISBN-13: 978-954-400-773-7 (9789544007737) ISBN-10: 954-400-773-3 (9544007733) Pages: 1122 Language: English Published: Sofia, 2013 Tags: book; free book; ebook; e-book; programming; computer programming; programming concepts; programming principles; tutorial; C#; data structures; algorithms; Intro C#; C# book; book C#; CSharp; CSharp book; programming book; book programming; textbook; learn C#; study C#; learn programming; study programming; how to program; programmer; practical programming guide; software engineer; software engineering; computer programming; software developer; software technologies; programming techniques; logi cal thinking; algorithmic thinking; developer; software development; programming knowledge; programming skills; programming language; basics of programming; presentations; presentation slides; coding; coder; source code; compiler; development tools; code decompiler; JustDecompile; debugging code; debugger; Visual Studio; IDE; development environment; bug fixing; class library; API; C#; .NET; .NET Framework; types; variables; operators; expressions; statements; value types; reference types; type conversion; console; console input; console output; console application; conditional statements; if; if-else; switch-case; loops; whole; do-while; for loops; foreach; nested loops; arrays; matrices; multidimensional arrays; numeral systems; binary numbers; decimal numbers; hexadecimal numbers; representations of numbers; methods; method invocation; parameters; recursion; iteration; recursive algorithms; classes; objects; fields; constructors; properties; static fields; static methods; static constructor; static members; namespaces; exceptions; exception handling; stack trace; catch exception; throw exception; try-catch; try-finally; using statement; strings; text processing; StringBuilder; escaping; System.String; regular expressions; string formatting; OOP; object-oriented programming; access modifiers; public; private; protected; internal; this keyword; const fields; readonly fields; default constructor; implicit constructor; overloading; method overloading; constructor overloading; automatic properties; read-only properties; constants; enumerations; inner classes; nested classes; generics; generic types; generic methods; text files; streams; files; StreamReader; StreamWriter; data structures; ADT; abstract data structure; linear data structures; list; linked list; static list; doubly-linked list; array list; stack; queue; deque; trees; graphs; binary tree; binary search tree; balanced tree; balanced search tree; B-tree; red-black tree; tree traversal; ordered balanced search tree; graph representation; list of edges; list of successors; adjacency matrix; depth-first search; DFS; breadth-first search; BFS; dictionary; hash table; associative array; hash function; collision resolution; set; multi set; bag; multi bag; multi dictionary; algorithm complexity; asymptotic notation; time complexity; memory complexity; execution time; performance; collection classes; .NET collections; Wintellect Power Collections; OOP; principles; abstraction; encapsulation; polymorphism; abstract class; interface; operation contract; virtual method; method overriding; cohesion; strong cohesion; coupling; loose coupling; spaghetti code; object-oriented modeling; UML; use-case diagram; sequence diagram; statechart diagram; activity diagram; design patterns; singleton; factory method; code quality; high-quality code; code conventions; naming identifiers; variable names; method names; naming classes; code formatting; high-quality classes; high-quality methods; variable scope; variable span; variable lifetime; control-flow statements; defensive programming; assertions; code documentation; documentation; self- documenting code; code refactoring; lambda expressions; LINQ; extension methods; anonymous types; LINQ queries; data filtering; data searching; data sorting; data grouping; problem solving; problem solving methodology; problems and solutions; generating ideas; task decomposition; algorithm efficiency; writing code; code testing; border cases testing; borderline cases; performance testing; regression testing; exercises; problems; solutions; programming guidelines; programming problems; programming exercises; good programmer; efficient programmer; pragmatic programmer; Nakov; Svetlin Nakov; Software Academy; Bulgaria; Bulgarian book; BG book; Bulgarian C# book; Kolev; Vesselin Kolev; Dilyan Dimitrov; Hristo Germanov; Iliyan Murdanliev; Mihail Stoynov; Mihail Valkov; Mira Bivas; Nikolay Kostov; Nikolay Nedyalkov; Nikolay Vassilev; Pavel Donchev; Pavlina Hadjieva; Radoslav Ivanov; Radoslav Kirilov; Radoslav Todorov; Stanislav Zlatinov; Stefan Staev; Teodor Bozhikov; Teodor Stoev; Tsvyatko Konov; Vesselin Georgiev; Yordan Pavlov; Yosif Yosifov, ISBN 9789544007737, ISBN 9544007733, ISBN 978-954-400-773-7, ISBN 954-400-773-3 Book Front Cover
Contents Contents .............................................................................................. 2 Detailed Table of Contents .................................................................. 5 Preface .............................................................................................. 13 Chapter 1. Introduction to Programming........................................... 69 Chapter 2. Primitive Types and Variables ........................................ 111 Chapter 3. Operators and Expressions ............................................. 139 Chapter 4. Console Input and Output .............................................. 165 Chapter 5. Conditional Statements .................................................. 195 Chapter 6. Loops ............................................................................. 211 Chapter 7. Arrays ............................................................................ 235 Chapter 8. Numeral Systems ........................................................... 265 Chapter 9. Methods ......................................................................... 293 Chapter 10. Recursion ..................................................................... 351 Chapter 11. Creating and Using Objects .......................................... 385 Chapter 12. Exception Handling ...................................................... 415 Chapter 13. Strings and Text Processing ......................................... 457 Chapter 14. Defining Classes ........................................................... 499 Chapter 15. Text Files ...................................................................... 615 Chapter 16. Linear Data Structures ................................................. 641 Chapter 17. Trees and Graphs ......................................................... 681 Chapter 18. Dictionaries, Hash-Tables and Sets .............................. 727 Chapter 19. Data Structures and Algorithm Complexity .................. 769 Chapter 20. Object-Oriented Programming Principles ..................... 807 Chapter 21. High-Quality Programming Code .................................. 853 Chapter 22. Lambda Expressions and LINQ ..................................... 915 Chapter 23. Methodology of Problem Solving .................................. 935 Chapter 24. Sample Programming Exam – Topic #1 ........................ 985 Chapter 25. Sample Programming Exam – Topic #2 ...................... 1041 Chapter 26. Sample Programming Exam – Topic #3 ...................... 1071 Conclusion ..................................................................................... 1119
FUNDAMENTALS OF COMPUTER PROGRAMMING WITH C# (The Bulgarian C# Programming Book) Svetlin Nakov & Co. Dilyan Dimitrov Hristo Germanov Iliyan Murdanliev Mihail Stoynov Mihail Valkov Mira Bivas Nikolay Kostov Radoslav Kirilov Radoslav Todorov Stanislav Zlatinov Stefan Staev Svetlin Nakov Teodor Bozhikov Teodor Stoev Nikolay Nedyalkov Tsvyatko Konov Nikolay Vasilev Pavel Donchev Pavlina Hadjieva Radoslav Ivanov Vesselin Georgiev Veselin Kolev Yordan Pavlov Yosif Yosifov Sofia, 2013
FUNDAMENTALS OF COMPUTER PROGRAMMING WITH C# (The Bulgarian C# Programming Book) © Svetlin Nakov & Co., 2013 The book is distributed freely under the following license conditions: 1. Book readers (users) may: - distribute free of charge unaltered copies of the book in electronic or paper format; - use portions of the book and the source code examples or their modifications, for all intents and purposes, including educational and commercial projects, provided they clearly specify the original source, the original author(s) of the corresponding text or source code, this license and the website www.introprogramming.info; - distribute free of charge portions of the book or modified copies of it (including translating the book into other languages or adapting it to other programming languages and platforms), but only by explicitly mentioning the original source and the authors of the corresponding text, source code or other material, this license and the official website of the project: www.introprogramming.info. 2. Book readers (users) may NOT: - distribute for profit the book or portions of it, with the exception of the source code; - remove this license from the book when modifying it for own needs. All trademarks referenced in this book are the property of their respective owners. Official Web Site: http://www.introprogramming.info ISBN 978-954-400-773-7
Detailed Table of Contents Contents .............................................................................................. 2 Detailed Table of Contents .................................................................. 5 Preface .............................................................................................. 13 About the Book ............................................................................................. 13 C# and .NET Framework ................................................................................ 17 How То Read This Book? ................................................................................ 22 Why Are Data Structures and Algorithms Emphasized? ...................................... 25 Do You Really Want to Become a Programmer? ................................................. 26 A Look at the Book’s Contents ........................................................................ 29 History: How Did This Book Come to Be? ......................................................... 38 Authors and Contributors ............................................................................... 40 The Book Is Free of Charge! ........................................................................... 53 Reviews ....................................................................................................... 53 License ........................................................................................................ 63 Resources Coming with the Book ..................................................................... 65 Chapter 1. Introduction to Programming........................................... 69 In This Chapter ............................................................................................. 69 What Does It Mean "To Program"? .................................................................. 69 Stages in Software Development ..................................................................... 71 Our First C# Program .................................................................................... 75 The C# Language and the .NET Platform .......................................................... 79 Visual Studio IDE .......................................................................................... 93 Alternatives to Visual Studio .......................................................................... 104 Decompiling Code ........................................................................................ 104 C# in Linux, iOS and Android ......................................................................... 107 Other .NET Languages .................................................................................. 107 Exercises ..................................................................................................... 108 Solutions and Guidelines ............................................................................... 108 Chapter 2. Primitive Types and Variables ........................................ 111 In This Chapter ............................................................................................ 111 What Is a Variable? ...................................................................................... 111 Data Types .................................................................................................. 111 Variables ..................................................................................................... 123 Value and Reference Types ............................................................................ 128 Literals ....................................................................................................... 131
6 Fundamentals of Computer Programming with C# Exercises ..................................................................................................... 135 Solutions and Guidelines ............................................................................... 136 Chapter 3. Operators and Expressions ............................................. 139 In This Chapter ............................................................................................ 139 Operators .................................................................................................... 139 Type Conversion and Casting ......................................................................... 152 Expressions ................................................................................................. 158 Exercises ..................................................................................................... 160 Solutions and Guidelines ............................................................................... 161 Chapter 4. Console Input and Output .............................................. 165 In This Chapter ............................................................................................ 165 What Is the Console? .................................................................................... 165 Standard Input-Output ................................................................................. 169 Printing to the Console .................................................................................. 169 Console Input .............................................................................................. 183 Console Input and Output – Examples ............................................................ 190 Exercises ..................................................................................................... 192 Solutions and Guidelines ............................................................................... 193 Chapter 5. Conditional Statements .................................................. 195 In This Chapter ............................................................................................ 195 Comparison Operators and Boolean Expressions .............................................. 195 Conditional Statements "if" and "if-else" ......................................................... 200 Conditional Statement "switch-case" ............................................................... 206 Exercises ..................................................................................................... 208 Solutions and Guidelines ............................................................................... 209 Chapter 6. Loops ............................................................................. 211 In This Chapter ............................................................................................ 211 What Is a "Loop"? ........................................................................................ 211 While Loops ................................................................................................. 211 Do-While Loops ............................................................................................ 216 For Loops .................................................................................................... 221 Foreach Loops ............................................................................................. 225 Nested Loops ............................................................................................... 226 Exercises ..................................................................................................... 231 Solutions and Guidelines ............................................................................... 233 Chapter 7. Arrays ............................................................................ 235 In This Chapter ............................................................................................ 235 What Is an "Array"? ...................................................................................... 235 Declaration and Allocation of Memory for Arrays .............................................. 235 Access to the Elements of an Array ................................................................. 238 Reading an Array from the Console ................................................................ 241
Detailed Table of Contents 7 Printing an Array to the Console ..................................................................... 243 Iteration through Elements of an Array ........................................................... 244 Multidimensional Arrays ................................................................................ 246 Arrays of Arrays ........................................................................................... 253 Exercises ..................................................................................................... 257 Solutions and Guidelines ............................................................................... 259 Chapter 8. Numeral Systems ........................................................... 265 In This Chapter ............................................................................................ 265 History in a Nutshell ..................................................................................... 265 Numeral Systems ......................................................................................... 266 Representation of Numbers ........................................................................... 276 Exercises ..................................................................................................... 289 Solutions and Guidelines ............................................................................... 290 Chapter 9. Methods ......................................................................... 293 In This Chapter ............................................................................................ 293 Subroutines in Programming .......................................................................... 293 What Is a "Method"? ..................................................................................... 293 Why to Use Methods? ................................................................................... 294 How to Declare, Implement and Invoke a Method? ........................................... 295 Declaring Our Own Method ............................................................................ 295 Implementation (Creation) of Own Method ...................................................... 300 Invoking a Method........................................................................................ 301 Parameters in Methods ................................................................................. 303 Returning a Result from a Method .................................................................. 328 Best Practices when Using Methods ................................................................ 345 Exercises ..................................................................................................... 347 Solutions and Guidelines ............................................................................... 348 Chapter 10. Recursion ..................................................................... 351 In This Chapter ............................................................................................ 351 What Is Recursion? ....................................................................................... 351 Example of Recursion ................................................................................... 351 Direct and Indirect Recursion ......................................................................... 352 Bottom of Recursion ..................................................................................... 352 Creating Recursive Methods ........................................................................... 352 Recursive Calculation of Factorial ................................................................... 353 Recursion or Iteration?.................................................................................. 355 Simulation of N Nested Loops ........................................................................ 356 Which is Better: Recursion or Iteration? .......................................................... 362 Using Recursion – Conclusions ....................................................................... 378 Exercises ..................................................................................................... 378 Solutions and Guidelines ............................................................................... 380 Chapter 11. Creating and Using Objects .......................................... 385
8 Fundamentals of Computer Programming with C# In This Chapter ............................................................................................ 385 Classes and Objects ...................................................................................... 385 Classes in C#............................................................................................... 387 Creating and Using Objects ........................................................................... 390 Namespaces ................................................................................................ 405 Exercises ..................................................................................................... 410 Solutions and Guidelines ............................................................................... 412 Chapter 12. Exception Handling ...................................................... 415 In This Chapter ............................................................................................ 415 What Is an Exception? .................................................................................. 415 Exceptions Hierarchy .................................................................................... 424 Throwing and Catching Exceptions ................................................................. 426 The try-finally Construct ................................................................................ 432 IDisposable and the "using" Statement ........................................................... 437 Advantages of Using Exceptions ..................................................................... 439 Best Practices when Using Exceptions ............................................................. 445 Exercises ..................................................................................................... 453 Solutions and Guidelines ............................................................................... 454 Chapter 13. Strings and Text Processing ......................................... 457 In This Chapter ............................................................................................ 457 Strings ........................................................................................................ 457 Strings Operations........................................................................................ 462 Constructing Strings: the StringBuilder Class ................................................... 480 String Formatting ......................................................................................... 488 Exercises ..................................................................................................... 491 Solutions and Guidelines ............................................................................... 496 Chapter 14. Defining Classes ........................................................... 499 In This Chapter ............................................................................................ 499 Custom Classes ............................................................................................ 499 Usage of Class and Objects............................................................................ 502 Organizing Classes in Files and Namespaces .................................................... 505 Modifiers and Access Levels (Visibility) ............................................................ 508 Declaring Classes ......................................................................................... 509 The Reserved Word "this" .............................................................................. 511 Fields .......................................................................................................... 512 Methods ...................................................................................................... 518 Accessing Non-Static Data of the Class ........................................................... 519 Hiding Fields with Local Variables ................................................................... 522 Visibility of Fields and Methods....................................................................... 524 Constructors ................................................................................................ 531 Properties ................................................................................................... 549 Static Classes and Static Members ................................................................. 559
分享到:
收藏