36,59 €
Enhance your programming skills by learning the intricacies of object oriented programming in C# 8
Key Features
Book Description
Object-oriented programming (OOP) is a programming paradigm organized around objects rather than actions, and data rather than logic. With the latest release of C#, you can look forward to new additions that improve object-oriented programming.
This book will get you up to speed with OOP in C# in an engaging and interactive way. The book starts off by introducing you to C# language essentials and explaining OOP concepts through simple programs. You will then go on to learn how to use classes, interfacesm and properties to write pure OOP code in your applications. You will broaden your understanding of OOP further as you delve into some of the advanced features of the language, such as using events, delegates, and generics. Next, you will learn the secrets of writing good code by following design patterns and design principles. You'll also understand problem statements with their solutions and learn how to work with databases with the help of ADO.NET. Further on, you'll discover a chapter dedicated to the Git version control system. As you approach the conclusion, you'll be able to work through OOP-specific interview questions and understand how to tackle them.
By the end of this book, you will have a good understanding of OOP with C# and be able to take your skills to the next level.
What you will learn
Who this book is for
This book is designed for people who are new to object-oriented programming. Basic C# skills are assumed, however, prior knowledge of OOP in any other language is not required.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 299
Veröffentlichungsjahr: 2019
Copyright © 2019 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor:Aaron LazarAcquisition Editor:Sandeep MishraContent Development Editor:Anugraha ArunagiriTechnical Editor: Neha PandeCopy Editor: Safis EditingLanguage Support Editors: Mary McGowan, Storm MannProject Coordinator:Ulhas KambaliProofreader: Safis EditingIndexer: Priyanka DhadkeGraphics:Tania DuttaProduction Coordinator:Aparna Bhagat
First published: February 2019
Production reference: 2140519
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78829-622-9
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Raihan Taher is a young, skilled software developer who has gained extensive experience by being involved in a variety of projects throughout his career. His particular areas of interest are web development and software architecture. His ability to write clean code and observe best practices in software development are his major assets. Throughout his relatively short career, he has worked for a number of renowned multinational companies, including Accenture, Quintiq (Dassault Systèmes), and SEB Pension. His desire to share his knowledge has encouraged him to write technical blogs, create online video courses, write books, and conduct technical training sessions. His courses, blog posts, and books have already been well received by many new developers. As regards the future, his vision is to discover and establish best practices for software development and share those with fellow developers. His ability to write quality software is what makes him accomplished. Aside from this, he is an avid reader and is excited by the challenge of learning new things. He always pushes himself to learn and implement new technologies in his work. Keeping himself up to date with new technologies and implementing those in his work makes him an expert in the area of cutting-edge technologies. He also loves to travel and explore adventurous places with his wife.
Gaurav Aroraa completed his M.Phil in computer science. He is a Microsoft MVP, a lifetime member of the Computer Society of India (CSI), an advisory member of IndiaMentor, and is certified as a scrum trainer/coach, XEN for ITIL-F, and APMG for PRINCE-F and PRINCE-P. Gaurav is an open source developer, and the founder of Ovatic Systems Private Limited. Recently, he was conferred as icon of the year—excellence in mentoring technology start-ups for the year 2018-19 by Radio City, a Jagran initiative, for his extraordinary work during his 20-year career in industry in the field of technology mentoring. You can tweet Gaurav on his Twitter handle: @g_arora.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Hands-On Object-Oriented Programming with C#
About Packt
Why subscribe?
Packt.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Overview of C# as a Language
Evolution of C#
Managed code
Generics
LINQ
Dynamics
Async/await
Compiler as a service
Exception filters
C# 8 and beyond
Architecture of .NET
Common Language Runtime
Common Type System
.NET framework class libraries
Just-in-time compiler
Fundamentals and syntax of C# language
Data types
Nullable types
Literals
Boolean
Integer
Real
Character
String
Programming syntax – conditions
If-else construct
Switch-case construct
goto statements
Programming syntax – loops
The while construct
The do-while construct
The for construct
The foreach construct
Contextual – break and continue statements
Break
Continue
Writing your first C# program in a console application
Visual Studio as an editor
Evolution of Visual Studio
Types of Visual Studio
Visual Studio Community
Visual Studio Professional
Visual Studio Enterprise
Visual Studio Code
Introduction to the Visual Studio IDE
New Project
Solution Explorer
Main workspace area
Output window
The Command and Immediate windows
Search option in IDE
Writing your first program in Visual Studio
How to debug
Debugging through code
Summary
Hello OOP - Classes and Objects
Classes in OOP
The general form of a class
Writing a simple class
Objects in OOP
How to create objects
Variables in C#
Methods in a class
Creating a method
Constructor of a class
Characteristics of OOP
Inheritance
Encapsulation
Abstraction
Polymorphism
Summary
Implementation of OOP in C#
Interfaces
The abstract class
The partial class
The sealed class
Tuples
Properties
Access specifiers for classes
Public
Private
Internal
Protected
Protected internal
Summary
Object Collaboration
Examples of object collaboration
Different types of object collaboration in C#
Case study
Dependency
Association
Aggregation
Composition
Inheritance
Summary
Exception Handling
Why we need exception handling in programming
Exception handling in C# programming
Basics of exception handling
Try and catch
What happens if you don't handle exceptions?
Multiple catch blocks
Using the throw keyword 
What does the finally block do?
Exception class
Some common exception classes
User-defined exceptions
The exception filter
Exception handling best practices
Summary
Events and Delegates
What is a delegate?
How to create and use delegates
Method group conversion
Using the static and instance methods as delegates
Multicasting
Covariance and contravariance
Events
Multicasting events
Event guidelines from .NET
Summary
Generics in C#
What are generics?
Why do we need generics?
Different constraints of generics
Base class constraints
Interface constraints
Reference type and value type constraints
Multiple constraints
Generic methods
Type-inferencing
Covariance and contravariance in generics
Covariance
Contravariance
Summary
Modeling and Designing Software
The importance of design diagrams
Different UML diagrams
Class diagrams
Inheritance
Association
Aggregation
Composition
Dependency
An example of a class diagram
Use case diagrams
The actor
The use case
The communication link
The system boundaries
An example of a use case diagram
A sequence diagram
An actor
A lifeline
An activation
A call message
A return message
A self message
A recursive message
A create message
A destroy message
A duration message
A note
An example of a sequence diagram
Summary
Visual Studio and Associated Tools
Visual Studio project types and templates
Visual Studio Editor and different windows
Editor window
Solution Explorer
Output window
Debugging windows
Breakpoints window
Exception Settings
Output
Diagnostic Tools
Immediate window
Python debugger window
Breakpoints, Call Stack Trace, and Watch
Breakpoint
Call Stack Trace
Watch window
Git in Visual Studio
Refactoring and code-optimization techniques
Rename
Changing the method signature
Encapsulate Field
Extract Method
Summary
Exploring ADO.NET with Examples
The fundamentals of ADO.NET
Data providers
Connection objects
The Command object
The DataReader object
DataAdapter
Connecting to various databases
SQL Server
The Oracle database
Working with DataReaders and DataAdapters
DataReaders
DataAdapters
Working with stored procedures
Working with the Entity Framework
What is an entity in the Entity Framework?
Different types of Entity properties
Scalar properties
Navigation properties
The code-first approach
The database-first approach
Using the Entity Framework
Transactions in SQL
Atomic
Consistent
Isolated
Durable
Summary
New Features in C# 8
Environment Setup
Nullable reference types
Async streams
Ranges and indices
Default implementation of interface members
Switch expressions
Target-typed new expressions
Summary
Understanding Design Patterns and Principles
Design principles
The single responsibility principle
The open-closed principle
The Liskov substitution principle
The interface segregation principle
The dependency inversion principle
Creational design patterns
The abstract factory pattern
The builder pattern
The factory method pattern
The prototype pattern
The singleton pattern
Structural design patterns
The adapter pattern
The decorator pattern
The facade pattern
The proxy pattern
Behavioral design patterns
The command pattern
The observer pattern
The strategy pattern
The MVC pattern
Summary
Git - The Version Control System
What is version control?
How Git works
Modified
Staged
Committed
Installing Git on Windows
The basics of Git
Git config
Git init
Git clone
Git status
Git add
Git commit
Git log
Git remote
Git push
Git pull
Git fetch
Branching in Git
Creating a branch
Viewing available branches
Changing branches
Deleting a branch
Merging in Git
Summary
Prepare Yourself - Interviews and the Future
Interview questions
What are the fundamental principles of object-oriented programming?
What is inheritance?
What is encapsulation?
What is abstraction?
What is polymorphism?
What is an interface?
What is an abstract class?
What is a sealed class?
What is a partial class?
What are the differences between interfaces and abstract classes?
What is the difference between method-overloading and method-overriding?
What are access modifiers?
What is boxing and unboxing?
What are the differences between a struct and a class?
What is an extension method in C# and how do we use it?
What is managed and unmanaged code?
What is a virtual method in C#?
What do you understand by value types and reference types in C#.NET?
What are design principles?
What is the single responsibility principle?
What is the Open/Closed principle?
What is the Liskov substitution principle?
What is the interface segregation principle?
What is the dependency inversion principle?
Interview and career tips
Improving your communication skills
Keep practicing
Things to learn next
Building the habit of reading
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Object-oriented programming (OOP) is a programming paradigm organized around objects rather than actions, and data rather than logic. With the newest release of C#, there are a number of new additions that improve OOP. This book aims to teach OOP in C# in an engaging and interactive way. After going through the book, you will have an understanding of the four pillars of OOP, which are encapsulation, inheritance, abstraction, and polymorphism, and be able to leverage the latest features of C# 8.0, such as Nullable Reference Types and Asynchronous Streams. You will then explore various design patterns, principles, and best practices in OOP.
This book is intended for people who are new to OOP. It assumes that you already have basic C# skills. No knowledge of OOP in any other language is expected.
Chapter 1, Overview of C# as a Language, covers a basic overview of the C# programming language to enable the beginner to understand the language constructs. The chapter will also explain why .NET exists as a framework and how to utilize the .NET framework in programs. The chapter will conclude by introducing Visual Studio as an editor for developing C# projects.
Chapter 2, Hello OOP - Classes and Objects, explains the most basic concepts of object-oriented programming. We start by explaining what a class is and how to write a class.
Chapter 3, Implementation of OOP in C#, covers the concepts that make C# an OOP language. This chapter covers some very important topics of the C# language and how to utilize those in real-life programming.
Chapter 4, Object Collaboration, covers object collaboration, what it is, how objects relate to one another in a program, and how many types of relationships exist between objects. We will also discuss dependency Collaboration, Association, and Inheritance.
Chapter 5, Exception Handling, covers how to handle exceptions in your code while executing it. We will explore the different types of exceptions and how to use the try/catch block to eliminate problems in your code.
Chapter 6, Events and Delegates, covers events and delegates. In this chapter, we will cover what an event is, what a delegate is, how an event is connected to a delegate, and their respective uses.
Chapter 7, Generics in C#, introduces a very interesting and important topic – generics. We will learn what generics are and why they are so powerful.
Chapter 8, Modeling and Designing Software, covers the different Unified Modeling Language (UML) diagrams used in software design. We will talk in detail about the most popular ones, including the class diagram, the use case diagram, and the sequence diagram.
Chapter 9, Visual Studio and Associated Tools, covers the best editor for C# programming. Visual Studio is a very rich IDE. It has some awesome features that make the life of a developer super productive. In this chapter, we will introduce the different projects and windows available in Visual Studio.
Chapter 10, Exploring ADO.NET with Examples, covers the ADO.NET classes, along with the fundamentals of various data adapters, stored procedures, and object relationship models through the Entity framework. We will also discuss transactions in ADO.NET.
Chapter 11, New Features in C# 8, covers new features of the C# language, which is improving day by day as C# language engineers incorporate additional features into the language. In 2019, Microsoft announced that C# 8.0 will be released, and outlined the new features that will come with this version. This chapter will discuss the new features that are going to be introduced in C# 8.0. We will talk about nullable reference types, async streams, ranges, default implementations of interface members, and several other topics.
Chapter 12, Understanding Design Patterns and Principles, contains information about design principles and some very popular and important design patterns.
Chapter 13, Git – The Version Control System, discusses the most popular version control system available today – Git. It is essential for all developers to learn Git.
Chapter 14, Prepare Yourself, Interview, and The Future, includes some of the most common interview questions and answers to those questions, so that you are prepared for your next interview. This chapter is mainly to give you an idea about potential interview questions.
The reader should have some prior knowledge of .NET Core and .NET Standard, along with a basic knowledge of C#, Visual Studio 2017 (as an IDE), version control, relational databases, and basic software design.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Object-Oriented-Programming-with-CSharp. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781788296229_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
With the introduction of modern-day programming practices, it is evident that developers are looking for more advanced constructs to help them to deliver the best software in the most effective way. Languages that evolve on top of frameworks are built to enhance the capabilities of the developers in a way that allows them to quickly build their code with less complexity so that the code is maintainable, yet readable.
There are many high-level object, oriented programming languages available on the market, but among them I would say one of the most promising is C#. The C# language is not new in the programming world and has existed for over a decade, but with the dynamic progress of the language itself creating so many newer constructs, it has already left some of the most widely accepted language competition behind. C# is an object-oriented, type-safe, general-purpose language that is built on top of the .NET framework that was developed by Microsoft and approved by the European Computer Manufacturers Association (ECMA) and the International Standards Organization (ISO). It is built to run on the Common Language Infrastructure and can interact with any other languages that are built based on the same architecture. Inspired by C++, the language is rich in delivering the best of breed applications without handling too many complexities in code.
In this chapter, we will cover the following topics:
Evolution of C#
Architecture of C#
Fundamentals and syntax of the C# language
Visual Studio as an editor
Writing your first program in Visual Studio
C# has been one of the most dynamic languages in recent times. This language is open source and mostly driven by a group of software engineers, who recently came up with lots of major changes to enhance the language and provide features to handle the complexities in the languages that exist. Some of the major enhancements that have been put forward for the language include Generics, LINQ, Dynamics, and the async/await pattern:
In the preceding diagram, we can see how the language has evolved from its inception with managed code in C# 1.0, to async programming constructs that were introduced in C# 5.0, to modern-day C# 8. Before going further, let's look at some of the highlights of C# in its different stages of evolution.
The phrase managed code came into being after Microsoft declared the .NET framework. Any code running in a managed environment is handled by Common Language Runtime (CLR), which keeps
Generics is a concept that was introduced with C# 2.0 and allows template type definition and type parameters. Generics allow the programmer to define types with open-ended type parameters that dramatically changed the way that programmers write code. The type-safety with dynamic typed generic templates improves readability, reusability, and code performance.
The third installment of the C# language introduced Language Integrated Query (LINQ), a new construct of queries that can be run over object structures. LINQ is very new to the programming world and gives us a glimpse of functional programming on top of object-oriented general programming structure. LINQ also introduced a bunch of new interfaces in the form of the IQueryable interface, which introduced a number of libraries that can interact with the external world using LINQ. LINQ was boosted with the introduction of Lambda expressions and expression trees.
The fourth instalment also provides a completely new construct. It introduces the dynamic language structure. The dynamic programming capability helps the developer to defer the programming calls to runtime. There is a specific syntactic sugar that was introduced in the language that compiles the dynamic code on the same runtime. The version also puts forward a number of new interfaces and classes that enhance its language capabilities.
With any language, threading or asynchronous programming is a pain. When dealing with asynchrony, the programmers have to come across many complexities that reduce the readability and maintainability of the code. With the async/await feature in the C# language, programming in an asynchronous way is as simple as synchronous programming. The programming has been simplified, with all of the complexities handled by the compiler and the framework internally.
Microsoft has been working on how some parts of the source code of the compiler can be opened up to the world. Consequently, as a programmer, you are capable of querying the compiler on some of its internal work principles. C# 6.0 introduced a number of libraries that enable the developer to get an insight into the compiler, the binder, the syntax tree of the program, and so on. Although the features were developed for a long time as the Roslyn project, Microsoft have finally released it to the external world.
C# 6.0 is adorned with a lot of smaller features. Some of the features give the developers an opportunity to implement complex logic with simple code, while some of them enhance the overall capabilities of the language. Exception filters are newly introduced with this version and give a program the capability to filter out certain exception types. The exception filters, being a CLR construct, have been hidden in the language throughout its lifetime, but were finally introduced with C# 6.0.
With C# being the most dynamic language in the market, it is constantly improving. With the newer features, such as nullable reference types, async streams, ranges and indices, interface members, and many other features that came with the latest version of C#, they have enhanced the basic features and helped programmers to take advantage of these new constructs, hence making their lives easier.
Note that, during the language's evolution, the .NET framework was also made open source. You can find the source code of the .NET framework at the following link: https://referencesource.microsoft.com/.
Even though it is a decade old, the .NET framework is still well-built and makes sure to make it tiered, moduler, and hierarchical. Each tier provides specific functionalities to the user—some in terms of security and some in terms of language capabilities. The tiers produce a layer of abstraction to the end users and hide most of the complexities of the native operating system as much as possible. The .NET framework is partitioned into modules, with each of them having their own distinct responsibilities. The higher tiers request specific capabilities from the lower tiers and hence it is hierarchical.
Let's look at a diagram of the .NET architecture:
The preceding diagram depicts how the .NET framework architecture is laid out. On its lowest level, it is the operating system that interacts with the kernel APIs that are present in the operating system. The Common Language Infrastructure connects with the CLR, which provides services that monitor each code execution and managed memory, handles exceptions, and ensures that the application behaves as intended. Another important goal of the infrastructure is language inter-operability. The common language runtime is yet again abstracted with the .NET class libraries. This layer holds the binaries that the language is built on, and all of the compilers built on top of the libraries provide the same compiled code so that the CLR can understand the code and interact easily with one another.
Before going further, let's quickly look at some of the key aspects on which languages are built on the .NET framework.
The CLR provides an interfacing between the underlying unmanaged infrastructure with the managed environment. This provides all of the basic functionalities of the managed environment in the form of garbage collection, security, and interoperability. The CLR is formed with the just-in-time compiler, which compiles the assembly code that's produced with the specific compilers to the native calls. CLR is the most important portion of the .NET architecture.
As there is a layer of abstraction between the language and the framework, it is evident that each of the language literals are mapped to specific CLR types. For instance, the integer of VB.NET is the same as the int of C#, as both of them point to the same type, System.Int32. It is always preferred to use language types since the compiler takes care of the mapping of types. The CTS system is built as a hierarchy of types with System.Object at its apex. The Common Type System (CTS) is divided into two kinds, one of which is value types, which are primitives that are derived from System.ValueTypes, while anything other than that is a reference type. The value types are treated differently to the reference types. This is because while allocation of memory value types are created on a thread stack during execution, reference types are always created on the heap.
The framework class library lies in-between the language and the CLR, and therefore any type that's present in the framework is exposed to the language you code. The .NET framework is formed with a good number of classes and structures, exposing never-ending functionalities that you, as a programmer, can benefit from. The class libraries are stored in the form of binaries that can be referenced directly from your program code.
.NET languages are compiled twice. During the first form of compilation, the high-level language is converted into a Microsoft Intermediate Language (MSIL), which can be understood by the CLR, while the MSIL is again compiled during runtime when the program is executed. The JIT works inside the program runtime and periodically compiles the code that is expected to be required during execution.
Being a high-level language, C# is adorned with a lot of newer and updated syntax, which helps the programmer to write code efficiently. As we mentioned earlier, the type system that's supported by the language is divided into two types:
Value types
Reference types
The value types are generally primitive types that are stored in the stack during local execution for faster allocation and deallocation of memory. The value types are mostly used during the development of code and, consequently, this forms the major spectrum of the code altogether.
The basic data types of C# are divided into the following categories:
Boolean type:
bool
Character type:
char
Integer types:
sbyte
,
byte
,
short
,
ushort
,
int
,
uint
,
long
, and
ulong
Floating-point types:
float
and
double
Decimal precision:
decimal
String:
string
Object type:
object
These are primitive data types. These data types are embedded in the C# programming language.
Literals are also an important part of any program. C# language gives the developer different kinds of options that allow the programmer to specify literals in code. Let's take a look at the different types of literals that are supported.
Character literals need to be kept inside a single quote. The value of the literal can be as follows:
A character, for example,
c
A character code, for example,
\u0063
An escape character, for example,
\\
(the forward slash is an escape character)
