46,44 €
Acquire necessary skills in preparing for Microsoft certification and enhance your software development career by learning the concepts of C# programming
Key Features
Book Description
Programming in C# is a certification from Microsoft that measures the ability of developers to use the power of C# in decision making and creating business logic. This book is a certification guide that equips you with the skills that you need to crack this exam and promote your problem-solving acumen with C#.
The book has been designed as preparation material for the Microsoft specialization exam in C#. It contains examples spanning the main focus areas of the certification exam, such as debugging and securing applications, and managing an application's code base, among others. This book will be full of scenarios that demand decision-making skills and require a thorough knowledge of C# concepts. You will learn how to develop business logic for your application types in C#. This book is exam-oriented, considering all the patterns for Microsoft certifications and practical solutions to challenges from Microsoft-certified authors.
By the time you've finished this book, you will have had sufficient practice solving real-world application development problems with C# and will be able to carry your newly-learned skills to crack the Microsoft certification exam to level up your career.
What you will learn
Who this book is for
The book is intended to the aspirants of Microsoft certifications and C# developers wanting to become a Microsoft specialist. The book does not require the knowledge of C#, basic knowledge of software development concepts will be beneficial
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 466
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 authors, 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: Pavan RamchandaniAcquisition Editor: Shriram ShekharContent Development Editor: Ruvika RaoSenior Editor: Afshaan KhanTechnical Editor: Ketan KambleCopy Editor: Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer:Pratik ShirodkarProduction Designer: Deepika Naik
First published: October 2019
Production reference: 1311019
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78953-657-7
www.packt.com
Packt.com
Subscribe to our online digital library for full access to over 7,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
Fully searchable for easy access to vital information
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.
Simaranjit Singh Bhalla is currently working as a technical architect manager for KPMG. He previously worked as a solutions architect with SMS Management and Technology in Sydney, Australia. He also worked with Microsoft Global Services for a period of three and a half years.
He has around seven years of experience in C#. He has extensive experience in the development of the Microsoft technology stack. He has performed multiple successful engagements in C#, .NET, Azure, JavaScript, and CRM. He has completed certifications in .NET 4.0 Framework, .NET 4.5 MVC, programming in C#, Windows Azure and Web Services, and others.
SrinivasMadhav Gorthi is a multi-skilled senior consultant with over nine years' experience in Microsoft Dynamics CRM implementations with the expertise to architect, design, and implement end-to-end solutions and business outcomes. Madhav has more than 17 years' experience in Microsoft technologies. He is currently working as a Solutions Architect in Sydney, Australia. Madhav has worked in Microsoft gold partner companies, including Velrada and Accenture. He has also delivered many end-to-end Microsoft applications using C#, ASP.NET MVC, Azure, and JavaScript.
Aidan Temple is an experienced software engineer with a history of working in the gaming industry. He holds both a master's of professional practice in games development from Abertay University, and a Bachelor of Science degree in games software development from Glasgow Caledonian University. He has over 8 years' experience working with C# and C++.
Jasvinder Singh completed his Bachelor of Technology in IT from IIIT-Allahabad in 2008. His home town is Unnao, Uttar Pradesh, and he is currently based in Bangalore, India. He has around 11 years' IT experience in total and is currently working with Flipkart. He began his career by joining Microsoft as a software development engineer and has an abundance of experience of working in the product development domain industry.
His expertise lies in problem solving using algorithms and in AI. Apart from playing with his 3-year-old son, Avraj, he likes to travel and watches sci-fi films and documentaries.
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
Programming in C#: Exam 70-483 (MCSD) Guide
About Packt
Why subscribe?
Contributors
About the authors
About the reviewers
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
Learning the Basics of C#
Technical requirements
Comparing C# with C and C++
C# versus C 
C# versus C++ 
.NET Framework 
Languages/applications
The class library
Common Language Runtime (CLR)
.NET Framework release versions 
Visual Studio for C#
Basic structure of C#
Creating a basic program in C#
Summary
Questions
Answers
Understanding Classes, Structures, and Interfaces
Technical requirements
Access modifiers
Data types in C#
Value type variables
Simple types
Enum types
Struct types
Reference type variables
Structs versus classes
Interfaces and inheritance
Inheritance
Interfaces in C#
Summary
Questions
Answers
Understanding Object-Oriented Programming
Technical requirements
Understanding object-oriented programming
Understanding encapsulation
Code example
Understanding abstraction
Understanding inheritance
Method overriding
Abstract classes
Abstract versus virtual methods
Sealed classes
Understanding polymorphism
Static/compile-time polymorphism
Runtime polymorphism
Summary 
Questions
Answers
Implementing Program Flow
Technical requirements
Understanding operators
Unary operators
Relational operators
Equality operators
Shift operators
Logical, conditional, and null operators
Understanding conditional/selection statements
if...else
switch..case..default
break
goto
continue
Iteration statements
do...while
for
Initializer section
Condition section
Iteration section
Examples of rare usage for statements
foreach...in
while
Summary
Questions
Answers
Further reading
Creating and Implementing Events and Callbacks
Technical requirements
Understanding delegates
Instantiating a delegate
Initiating delegates using NamedMethod
Initiating a delegate using anonymous functions
Lambda expressions
Anonymous methods
Variance in delegates
Built-in delegates
Multicast delegates
Handling and raising events
Summary
Questions
Answers
Further reading
Managing and Implementing Multithreading
Technical requirements
Understanding threads and the threading process
Managing threads
Thread properties
Parameterized threads
Foreground and background threads
Thread states
Destroying threads
Thread pools
Thread storage
Synchronizing data in multithreading
Multithreading
Parallel programming
TPL
Data parallelism
Using tasks
Using the Parallel class
PLINQ
Asynchronous programming with async and await
Summary
Questions
Answers
Further reading
Implementing Exception Handling
Technical requirements
Exceptions and handling exceptions in code
Using exceptions
Exception handling
Compiler-generated exceptions
Custom exceptions
Summary
Questions
Answers
Further reading
Creating and Using Types in C#
Technical requirements
Creating types
Types in C# 
Unsafe code and the use of pointer types
Choosing the type of variable
Static variables
Static member variables
Static methods
Constructors
Named parameters
Optional parameters
Generics types
Consuming data types in C#
Boxing and unboxing 
Type conversions in C#
Implicit conversion
Explicit conversion
Enforcing encapsulation
Manipulating strings
StringBuilder
StringReader and StringWriter
String searching 
Overview of reflection
Summary 
Questions
Answers
Managing the Object Life Cycle
Technical requirements
Managed code versus unmanaged code
Garbage collection
Managed heap
Generations
The mark-compact algorithm
Calling garbage collection
Managing unmanaged resources
The finalization mechanism
The IDisposable interface
The using block
Summary
Questions
Answers
Find, Execute, and Create Types at Runtime Using Reflection
Technical requirements
Attributes
Using attributes
Creating custom attributes
Retrieving metadata
Reflection
Invoking methods and using properties
Summary
Questions
Answers
Validating Application Input
Technical requirements
The importance of validating input data
Data integrity
Parsing and converting
Regular expressions
JSON and XML
Summary
Questions
Answers
Performing Symmetric and Asymmetric Encryption
Technical requirements
Cryptography
Symmetric encryption
Asymmetric encryption
Digital signatures
Hash values
Summary
Questions
Answers
Managing Assemblies and Debugging Applications
Technical requirements
Assemblies
Assembly contents and manifest
Target .NET Framework
Signing assemblies
Versioning assemblies
Version number
Debugging the C# application
Tracing
Summary
Questions
Answers
Performing I/O Operations
Technical requirements
File I/O operations
Working with System.IO helper classes
Drives and directories
Checking whether the directory exists
Creating a directory
Looping through the files
Working with files
Checking whether a file exists
Moving a file from one location to another
Copying a file from one location to another
Deleting a file 
Stream object
FileStream
Exception handling
Reading data from a network
WebRequest and WebResponse
Asynchronous I/O operations
Async operations on file
Using the await statement for parallel asynchronous calls
Summary 
Questions
Answers
Using LINQ Queries
Technical requirements
Introducing LINQ
Queries
Understanding language features that make LINQ possible
Implicitly typed variables
Object initialization syntax
Lambda expressions
Extension methods
Anonymous types
Understanding LINQ query operators
Select and SelectMany
The join operator
The orderby operator
Average
GroupBy
Understanding LINQ behind the scenes
Using LINQ to XML
Querying XML
Creating XML
Updating XML
Summary 
Questions
Answers
Serialization, Deserialization, and Collections
Technical requirements
Serialization and deserialization
XmlSerializer
Binary serialization
Working with collections
Arrays
Lists
Dictionary
Queues and stacks
Choosing a collection
Summary 
Questions
Answers
Mock Test 1
Mock Test 2
Mock Test 3
Assessments
Chapter 17 – Mock Test 1
Chapter 18 – Mock Test 2
Chapter 19 – Mock Test 3 
Other Books You May Enjoy
Leave a review - let other readers know what you think
The MCSD 70-483 exam is an entry-level Microsoft certification exam for C# developers that is widely used to measure their expertise in the field of C# programming. This book is a certification guide to prepare you for the skills that are evaluated in the certification exam and also promotes building problem-solving acumen with C#. Every chapter in the book has been designed as preparation material for the Microsoft MCSD 70-483 exam.
For those who don't have much experience of working in C#, we have added some chapters at the start of the book that will provide basic knowledge about C# programming. This knowledge will not only help you to pass the certification but will also help you to become a better C# developer.
The book is designed for both experienced developers and people new to C# who are intending to undertake the 70-483 Programming in C# certification exam in the near future. The book provides extensive knowledge of all the topics that are evaluated in the exam. To drive better understanding, each chapter in the book is accompanied by code examples along with assessment questions.
To make the path of learning C# easier for beginners, we have also tried to address the basics of C# and .NET Framework in the first three chapters of the book. To get the most value out of the book, you are expected to have a fair understanding of any programming language; for example, C, C++, or C#.
Chapter 1, Learning the Basics of C#, focuses on the basics of the C# language. In this chapter, you will learn about the underlying .NET Framework architecture and how all the components, such as the garbage collector, common language runtime, base libraries, and so on, interact with each other. We will analyze the similarities between C# and other programming languages such as C++ and C. We will also look at features that make C# different than C++ and C. Finally, using a very basic Hello World program, you will learn about the different components of a C# program, such as classes, namespaces, assemblies, and so on.
Chapter 2, Understanding Classes, Structures, and Interfaces, expands on the first chapter and covers some more basics of a C# application. In this chapter, you will learn about the different access modifiers available in a C# program, and also how they can be used to achieve code structure and reduced complexity. We will also look at the different primitive data types available in C#. While looking at the class and struct variables, we will see the difference between a reference type variable and a data type variable. We will then look at inheritance, which is an important aspect of C# programming. We will cover how inheritance is implemented in C# and how it differs from the implementation of an interface.
Chapter 3, Understanding Object-Oriented Programming, focuses on the four pillars of Object-Oriented Programming (OOP). Using examples, you will learn how each of those pillars – encapsulation, polymorphism, abstraction, and inheritance—is implemented. While looking at inheritance, we will expand on the learning of Chapter 2, Understanding Classes, Structures, and Interfaces, and look at some other critical aspects, such as method overriding, virtual methods, and sealed and abstract classes. While looking at polymorphism, we will learn how we can implement both compile/static and runtime polymorphism in C# programs.
Chapter 4, Implementing Program Flow, focuses on how a developer can manage program flow in C#. In other words, this chapter helps you to understand how to control the program and make decisions using the statements available in C#. We will cover various Boolean expressions such as if/else and switch, which control the flow of code based upon conditions. This chapter also provides an overview of various operators, such as the conditional operator and the equality operator (<, >, and ), which govern the flow of code. Apart from operators and decision-making statements, this chapter helps you gain an understanding of iterating through collections (for loop, while loop, and so on) and explicit jump statements.
Chapter 5, Creating and Implementing Events and Callbacks, focuses on events and callbacks in C#, which are important and give more control over the program. You'll learn about the publish/subscribe model using events and callbacks, and focus on delegates. Then, we will move on to different ways of initiating delegates and lambda expressions. We will also spend some time on a new operator called the lambda operator, which is used in Lambda expressions.
Chapter 6, Managing and Implementing Multithreading, focuses on handling responsiveness in long-running programs and how we can keep the user notified about their progress. We'll also look at how we can use the multi-core processing power that comes with every computer effectively. We will spend time looking at threads, thread properties, and how to use tasks and perform multithreaded operations.
Chapter 7, Implementing Exception Handling, focuses on understanding how to structure your program in a way that helps it to run in all scenarios; how we can handle unhandled exceptions; how to use the try, catch, and finally keywords and clean up resources once execution is completed. After reading this chapter, you will understand exceptions and how to use them in your program. You'll also be able to create custom exceptions.
Chapter 8, Creating and Using Types in C#, focuses on the different types of variables available in C#. In Chapter 2, Understanding Classes, Structures, and Interfaces, we introduced users to the reference and data type variables available in C#. In this chapter, we will expand on that knowledge and learn how both variable types are maintained in memory. We will look at the managed heap memory structure, which is used for saving reference type variables. We will also look at the use of variable types pointer types in C#. Using pointers, we can implement memory-related operations that are otherwise considered unsafe in C#. We will also look at some important features in C#, such as properties, named arguments, and optional arguments, which are available in C# programming. We will look at how we can convert value-type variables to objects using boxing and similarly use unboxing to convert the object back to a value-type variable. We will then look at the different operations that are possible on a string representation in C#. We will also look at how we can use stringbuilder to optimize the performance of a C# program.
Chapter 9, Managing the Object Life Cycle, focuses on how the garbage collector manages the allocation and release of memory in .NET Framework. In this chapter, you will learn the difference between managed and unmanaged code in C#. We will look at mark-compact algorithms, used by garbage collectors for the allocation and release of memory. We will look at the possible ways we can manage the memory allocated to unmanaged code. We will also look at how we can implement finalization in a C# application and the performance implications of doing so. We will introduce the IDisposable interface and understand its differences from a finalize block. We will also look at code examples, in which we will combine both the IDisposable interface and a finalize block to achieve the best possible memory management for a C# application. Finally, we will look at the use of the using block in a C# application.
Chapter 10, Find, Execute, and Create Types at Runtime Using Reflection, focuses on understanding how .NET Framework allows us to read/create metadata and how we can use reflection to read metadata and process it during runtime. We will focus on using attributes, creating custom attributes, and how we can retrieve attribute information at runtime. We'll also cover how we can use reflection to create types, access properties, and invoke methods.
Chapter 11, Validating Application Input, focuses on validating input from the different kinds of users who'll access your application and how we can avoid the application crashing based on user input. The purpose of this chapter is to understand the importance of validating input data in your application, the different validation techniques available in .NET Framework, and ways to validate JSON data and XML data.
Chapter 12, Performing Symmetric and Asymmetric Encryption, focuses on how to keep information secure, what measures we can take while transmitting information over the internet, and understanding cryptography to encrypt and decrypt plain text. After reading this chapter, you will understand how to encrypt and decrypt text and be familiar with the different algorithms available in .NET Framework to perform such exercises.
Chapter 13, Managing Assemblies and Debugging Applications, focuses on how to manage .NET assemblies, debugging applications, and how to use tracing. This chapter covers validation techniques we have already learned and exception handling for those scenarios, as well as monitoring code blocks. We'll also look at Visual Studio features or tools for debugging an application. After that, we'll look at the versioning of assemblies and how we can have the same assembly side by side, as well as how we can distribute those assemblies without impacting others.
Chapter 14, Performing I/O Operations, focuses on how I/O operations are performed in a C# application. In this chapter, we will look at the different operations possible in C# to access data in I/O files as well as operations coming from external web services. Using code examples, you will see how we can use the System.IO helper class to read/write data from a file. We will also look at the helper classes of File and FileInfo provided in C# for performing I/O operations. We will then look at the WebRequest and WebResponse helper classes, which help us to interact with data coming from external services/applications. Finally, we will look at how we can execute these operations asynchronously in an application.
Chapter 15, Using LINQ Queries, focuses on how LINQ queries are implemented in C#. In this chapter, you will be introduced to the basics of a LINQ query, gaining an understanding of the different components and how they are constructed in .NET Framework. We will then look at the features in C# that help with the implementation of LINQ queries. Some of those features are necessary while some of them help us to get the best outcomes from LINQ queries. Using code examples, you will come to understand the implementation of implicitly typed variables, object initialization syntax, Lambda expressions, extension methods, and anonymous types. We will then look at the different operations available in LINQ queries. Using code examples, you will learn about the different scenarios in which you can use each of these operators. Finally, we will look at how you can use LINQ queries to perform operations on an XML file.
Chapter 16, Serialization, Deserialization, and Collections, focuses on different serialization and deserialization approaches, such as XML serialization, JSON serialization, and binary serialization, available in .NET Framework. We will also look at how we can define data contracts in web services so that data can be exchanged between different applications. We will then look at different collection objects, such as arrays, lists, dictionary, queues, and stacks, available in C# and understand how they can be used to store and consume data.
To get the best possible outcome from this book, it's advisable for you to have the following:
A basic understanding of software development
A basic understanding of any common programming language, such as C, C++, or C#
For the entirety of this book, we will be going through different code examples in C# and will be using Visual Studio 2017 Community Edition for the code examples. The following hardware requirements are essential for Visual Studio:
Operating system:
Windows 10 or higher
Windows Server 2016: Standard and Datacenter
Windows 8.1
Windows Server 2012 R2: Essential, Standard, and Datacenter
Windows 7 SP1
Hardware requirements:
Minimum 2 GB of RAM
1.8 GHZ or faster processor
Additional requirements:
Administrative rights of the system
.NET Framework 4.5 or higher
Visual Studio: All of the code examples in this book have been compiled on Visual Studio Community Edition 2017 (
you can also use a higher version of Visual Studio)
. It's available for installation at
https://www.visualstudio.com/downloads/
.
For better understanding, it's advisable that readers go through all the assessments at the end of each chapter as well as the mock tests available at the end of the book.
It's also advisable for readers to go through the code examples available for each of the chapters and do the self-practice after each chapter.
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.packtpub.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.
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/Programming-in-C-Sharp-Exam-70-483-MCSD-Guide. 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://static.packt-cdn.com/downloads/9781789536577_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "By default, a method by the name of Main will also be added to the class."
A block of code is set as follows:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "To create a new project, click on File | New Project and select Console App (.NET Framework) as the project type."
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.packtpub.com/support/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.
In simple terms, programming is the art of writing a set of commands that instruct a computer to execute a particular task. In the early days, programming capabilities were limited due to memory and speed restrictions. Due to this, programmers wrote crude and simple tasks that did elementary jobs. With time and with more enhancements, people started writing programs in procedural languages such as COBOL.
Although the languages did the work, the programs had some limitations. There was not much scope for writing reusable components or design patterns that could be used in different places in the application. Hence, the applications were difficult to maintain and scalability was a challenge.
As a result, efforts were made to develop high-level programming languages that could overcome all such challenges faced by procedural languages. With time, many different programming languages were devised. C was developed between 1972 and 1973. At the time, it was a low-level procedural language that depended upon the underlying platform, such as Linux or Windows. C also did not fully utilize the concept of object-oriented programming (which we will go through inChapter 3,Understanding Object-Oriented Programming).
C++ was introduced in 1998, and provided programmers with the ability to effectively use the concepts of object-oriented programming while still retaining the machine-level programming features provided by C. In this book, we will go through the different aspects of programming in C#. While retaining the OOP capabilities of C++, C# allows us to write programs independent of the underlying hardware implementation.
In this chapter, we will go over the basics of C#. We will review its underlying fundamentals and dive deep into the .NET Framework architecture. We will learn how common language runtime works to translate the application code to machine-level code. We will learn how C# is both different and similar to other languages, such as C and C++. We will then learn about the different components in a C# program, such as classes, namespaces, and assemblies. And, as a common tradition for any new language, we will look at the implementation of a Hello World program.
This chapter consists of the following topics:
Comparing C# with C and C++
.NET Framework
.NET Framework release versions
Visual Studio for C#
Basic structure of C#
Creating a basic program in C#
For a better understanding of the chapter, you require the following knowledge:
A basic understanding of software development
A basic understanding of common programming languages: C, C++ and C#
For the entirety of this book, we will be going through different code examples in C# and will be using Visual Studio 2017 Community Edition for the code examples. The following hardware requirements are essential for Visual Studio:
Operating system
:
Windows 10 or higher
Windows Server 2016: Standard and Datacenter
Windows 8.1
Windows Server 2012 R2: Essential, Standard, and Datacenter
Windows 7 SP1
Hardware requirements
:
Minimum 2 GB of RAM
1.8 GHz or faster processor
Additional requirements
:
Administrative rights of the system
.NET Framework 4.5
Visual Studio
: All code examples in this book have been compiled on Visual Studio Community Edition 2017. It's available for installation at:
https://www.visualstudio.com/downloads/
.
Sample code for this chapter can be found on GitHub at https://github.com/PacktPublishing/Programming-in-C-sharp-Exam-70-483-MCSD-Guide/tree/master/Chapter01.
In this section, we will explore how C# compares against other programming languages, such as C and C++. We will look at aspects that make C# similar, and also areas in which it differs from these languages.
If you have done some previous development on C# and C , you will realize that they follow similar code syntax, such as the use of semi-colons, and similar declarations of methods; the two languages are very different from one another. Just like in C, we can declare data variables with the same type, such as Char, and Integer. The following features make C# different from C:
Feature
C#
C
Object-oriented programming
Object-oriented programming is the main essence of any high-level programming language, and C# allows us to utilize the capabilities of OOP using the four main pillars of encapsulation, polymorphism, inheritance, and abstraction. In Chapter 3, Understanding Object-Oriented Programming, we will look at this in detail.
C as a programming language
does not support polymorphism, encapsulation, and inheritance.
It does not provide features
such as function overloading, virtual functions, and inheritance.
Exception handling
Exception handling is the process of handling runtime errors that occur during the execution of the application. C# provides us with exception handling features that help us handle these scenarios in a better way. In Chapter 7, Implementing Exception Handling, we will look at this in detail.
C also does not provide any exception handling features.
Type safety
Every variable declared in a program has a type. In a typical type-safe language during the program compilation stage itself, the compiler will validate the values being assigned to variables and raise a compile time error if an incorrect type is assigned to it. C# is a type-safe language. However, in Chapter 8, Creating and Using of Types in C#, we will learn that it also allows you to use pointers using a keyword, UnSafe.
C language implements type safety, albeit with some exceptions. There are certain in-built functions such as printf that do not enforce that only character strings are passed to them.
Let's now look at how C# compares against another language, C++. After exploring the comparison between C# and C++, we will also explore how the .NET Framework makes C# a platform-independent language compared to C and C++.
In most programming scenarios, C++ can be classified as an extension of C and can execute all the code that was written in C. It provides all the features of object-oriented programming while retaining the functionalities provided by C. There are several features that are common between C# and C++. Just as in C#, we can implement object-oriented programming, exception handling, and type safety in C++. However, there are also certain things that make C# different to C++ and more similar to Java.
Before we look at the differences and similarities between C# and C++, we must understand some key concepts pertaining to object-oriented programming.
The languages that implement object-oriented programming are classified in two categories:
Fully object-oriented languages
Pure object-oriented languages
A language is classified as a fully object-oriented programming language if it implements at least the four core pillars of Abstraction, Encapsulation, Polymorphism, and Inheritance.
On the other hand, a language can be defined as a pure object-oriented programming language when, apart from being fully object-oriented programming, it only contains classes and objects. This means that all methods, properties, and attributes declared must be inside a class and also should not have any predefined data types, such as char and int.
In the case of C#, we can have predefined data types. In Chapter 2, Understanding Classes, Structures, and Interfaces, we will look into those predefined data types in detail. This makes C# a fully object-oriented language and not a pure object-oriented language.
On the other hand, in the case of C++, we can define methods that are not part of any class. This, too, makes it a fully object-oriented language.
Now, let's look at some of the similarities and differences between C# and C++:
Feature
C#
C++
Object-oriented programming
As described previously, C# is a fully object-oriented language.
Similar to C#, C++ is also a fully object-oriented language.
Memory management
C# has got an inbuilt garbage collector that manages the allocation and deallocation of memory. In Chapter 9, Managing the Object Life Cycle, we will understand memory management in C# in detail.
C++ does not have a built-in garbage collector. Due to this, developers are responsible for handling the allocation and deallocation of memory.
Inheritance
C# does not support multiple inheritance. In Chapter 2, Understanding Classes, Structures, and Interfaces, we will learn what it means; however in simple terms, it means that a class can only inherit from one class at a time.
Compared to C# , C++ allows us to implement multi-level inheritance.
Use of pointers
Although C# allows us to use pointers in our code, we need to declare the code with a snippet of UnSafe. We will look into this in detail in Chapter 8, Creating and Using of Types in C#.
C++ allows us to use pointers anywhere without any implicit declaration in the code.
In the previous two sections, we saw how C# compares to both C and C++. However, there is one important difference that we haven't yet explored. That feature is platform independence and was one of the main reasons C# was introduced by Microsoft. When working with C and C++, we need to compile the code in accordance with the underlying platform features, such as the operating system.
Suppose we write an application in C or C++ and compile it. During the compilation stage, the compiler translates the code into a native language code that is only compatible with the underlying platform. This basically implies that an application in C++, developed and compiled on a Windows machine, will just be compatible with a Windows machine. If the compiled bits are used on a different system, such as Linux, it will not work there.
This difference is caused due to the varying nature of compilers and their compatibility with underlying operating systems, such as Linux and Windows. These are some of the common compilers in Linux and Windows that are available for C and C++:
Linux
: GCC, Failsafe C, and SubC
Windows
: Microsoft Windows SDK, Turbo C++, and
SubC
Before C# was developed, this platform dependence issue was a major disadvantage compared to some of the other programming languages, such as Java. In Java, when an application is compiled, it's not directly converted into machine code. Instead, it's converted into an intermediate language known as ByteCode. The ByteCode is platform-independent and can be deployed on different platforms.
When Microsoft introduced C#, they inculcated the same principle in the language. When an application written in C# is compiled, instead of being converted to the native code compatible with the machine, the application is first translated to an intermediate language commonly known as IL code.
After the IL code is generated, the Common Language Runtime (CLR) comes into effect. CLR is a runtime environment that sits in the memory of the underlying machine and converts the IL code to the native code, which is specific to the machine. This process is Just-In-Time (JIT) compilation. In the next section, we will look at the underlying platform of the .NET Framework, which handles all this for a C# application.
.NET Framework is a software development framework on which we can write a number of languages such as C#, ASP.NET, C++, Python, Visual Basic, and F#.
.NET Framework provides language interoperability across different programming languages. Applications written in .NET Framework execute in an environment or a virtual machine component known as CLR.
The following diagram illustrates the different components in .NET Framework:
In the previous diagram, note the following:
At the top of the hierarchy, we have applications or the program code that we write in .NET. It could be as simple as a
Hello World
console application program, which we will create in this chapter, or as complex as writing multi-threaded applications.
The applications are based upon a set of classes or design templates, which constitutes a class library.
The code written in these applications is then acted upon by CLR, which
makes use of the
Just in Time
(
JIT
) compiler to
convert the application code into machine code.
The machine code is specific to the underlying platform properties. So, for different systems, such as Linux or Windows, it will be different.
In the next section, we will the .NET Framework in detail learn how interact with each other.
Languages indicate the different types of applications that can be built in .NET Framework. If you are new to .NET Framework, you may not be familiar with some of the applications listed here:
ADO.NET
:
In an ADO.NET application, we write programs to access data from sources such as SQL Server, OLE DB, and XML sources.
ASP.NET
: In an ASP.NET application, we write programs to build web apps such as websites and services using C#, HTML, CSS, and so on.
CORE
:
In .NET Core applications, we write programs that support cross-platform functionality. The programs could be web apps, console applications, or libraries.
Windows Forms
: In Windows Forms applications, we write programs that provide client-side applications for desktops, tablets, and mobile devices.
WPF
: In WPF or Windows Presentation Foundation, we write programs that provide user interfaces in Windows-based applications. It runs only on Windows-supported platforms, such as Windows 10, Windows Server 2019, and Windows Vista.
WCF
: In WCF or Windows Communication Foundation, we write programs that provide a set of APIs, or in simpler terms, services, to exchange data between two distinct systems.
LINQ
: In LINQ, we write programs that provide data querying capabilities on .NET applications.
Parallel FX
: In Parallel FX, we write programs that support parallel programming. It involves writing programs that utilize the CPU's capabilities to the fullest by executing several threads in parallel to complete a task.
The class library in .NET Framework consists of a collection of interfaces, classes, and value types on which the applications are built.
These collections are organized in different containers known as namespaces. They are a set of standard class libraries that can be used for different purposes in an application. Here are some of the namespaces:
Microsoft.Sharp
: This contains a type that supports compilation and code generation for C# source code, and the type that supports conversion between Dynamic Language Runtime and C#.
Microsoft.Jscript
: This contains classes that support compilation and code generation using JavaScript.
Microsoft.VisualBasic
: This contains classes that support compilation and code generation for Visual Basic.
Microsoft.VisualC
: This contains classes that support compilation and code generation for Visual C++.
CLR is a runtime environment that sits in the memory of the underlying machine and converts the IL code to native code. The native code is specific to the underlying platform in which the code is running. This provides a platform independence feature in a typical application made on .NET Framework. Some of the other features provided by CLR are mentioned here:
Memory management
: CLR provides automatic allocation and release of memory across the application. Due to this, developers do not need to explicitly write code to manage memory. This eliminates issues that can lead to degradation of application performance due to memory leaks. CLR manages the allocation and removal of memory using a garbage collector, which manages the memory allocation in the following manner:
Allocating memory
: When an application is executed in CLR, it reserves a continuous space of memory for its execution. The reserved space is known as a managed heap. The heap maintains a pointer to the memory address where the next object defined in the process will be allocated.
Releasing memory
: During the runtime execution of the program, the garbage collector runs at scheduled times and examines whether the memory allocated in heaps are still in scope of program execution or not.
It determines whether the program is still using the memory on the basis of roots or the collection of memory objects are still in the scope of the program. If any memory allocation is not reachable as per the collection in the root, the garbage collector determines that the memory allocated in that memory space can be released.
We will look into memory management in detail in
Chapter 9
,
Manage the Object Life Cycle
.
Exception handling
: When an application is being executed, it may result in certain execution paths that could generate some errors in the application. Some of the common examples are as follows:
When an application tries to access an object such as a file that is not present in the specified directory path.
When an application tries to execute a query on the database but the connection between the application and the underlying database is broken/not open.
We will look into exception handling in detail when we go through
Chapter 7
,
Implementing Exception Handling
.
In the next section, we will look at the release history of .NET Framework and its compatibility with different versions of CLR and C#.
The first version of .NET Framework 1.0 was released in 2002. Just like .NET Framework, there are different versions of CLR and C# as well. The different versions of .NET Framework are compatible with some particular versions of both CLR and C#. The following table provides a compatibility mapping between the different .NET Framework versions and its compatible versions of CLR:
.NET Framework
CLR version
1.0
1.0
1.1
1.1
2.0/3.0/3.5
2.0
4.0/4.5/4.5.1/4.5.2/4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2/4.8
4
The following table matches the different versions of .NET Framework with its compatible C# version, and lists some of the important programming features that were released in that version of C#:
Version
.NET Framework
Important features in C#
C# 1.0/1.1/1.2
.NET Framework 1.0/1.1
First release of C#
C# 2.0
.NET Framework 2.0
Generics anonymous methods, Nullable types, and Iterators
C# 3.0
.NET Framework 2.0/3.0/3.5/4.0
Query expressions, Lambda expression, and Extension methods
C# 4.0
.NET Framework 2.0/3.0/3.5/4.0
Dynamic binding, Named/optional arguments, and Embedded interop types
C# 5.0
.NET Framework 4.5
Asynchronous members
C# 6.0
.NET Framework 4.6/4.6.2/4.7/4.7.1/4.7.2
Exception filters, String interpolation,
nameof
operator, and Dictionary initializer
C# 7.0/7.1/7.2/7.3
.NET Framework 4.6/4.6.2/4.7/4.7.1/4.7.2
Out variables, Pattern matching, Reference locals and returns, and Local functions
C# 8
.NET Framework 4.8
Read-only members and Default interface members
In the next section, we will look at Visual Studio, an IDE tool provided by Microsoft for building applications with .NET Framework, and some of its built-in features that can help us during the development phase.
Microsoft Visual Studio is an Integrated Development Environment (IDE) tool used by developers worldwide to develop, compile, and execute their .NET Framework applications. There are several features provided in the tool that help developers not only improve the quality of the application developed, but also greatly reduce the time of development.
Some of the key features of Visual Studio are mentioned here:
It uses Microsoft software development platforms such as Windows API, Forms, WPF, and Silverlight.
While writing code, it provides IntelliSense code-completion features, which help the developers write code efficiently.
It also provides a forms designer for building GUI applications, a class designer, and database schema designer.
It provides support for different source control systems, such as GitHub and TFS.
The current version of Visual Studio is 2017. For development purposes, Microsoft provides a Community Edition of Visual Studio, which is free of cost and can be used for non-commercial activities.
It's essential that before using the Community Edition, we go through the terms and conditions of use as well: https://visualstudio.microsoft.com/license-terms/mlt553321/.
In the next section, we will do a walk-through on the basic syntax involved in writing a basic C# application.
In this section, we will go over a basic programming syntax of a C# application, namely: classes, namespaces, and assemblies.
As C# is an object-oriented language, and at the basic level it contains building blocks known as classes. The classes interact with one another, and as a result, provide functionality at runtime. A class consists of two components:
Data attributes
: Data attributes refer to the different properties defined in the class object.
Methods
: Methods indicate the different operations that are to be executed in the class object.
As an example, we will look at the representation of a car as an object in C#. At a very basic level, a car will have attributes such as the following:
Make
: For example Toyota, Ford, or Honda.
Model
: For example Mustang, Focus, or
Beetle.
Color
: Color of the car, such as Red or
Black.
Mileage
: Distance covered per liter of fuel consumed.
Please note that a car can have more attributes, but as this example is just being used for the sake of explanation, we have included these basic attributes. While writing a C# application, all of these will be captured as attributes for the Car class.
Similarly, to make sure the Car class achieves all of the desired features, it will need to implement the following operations:
StartEngine
: This function represents how the car starts moving.
GainSpeed
: This function represents how the car accelerates.
ApplyBrake
: This function represents how the car applies brakes to slow down.
StopEngine
: This function represents how the car stops.
While writing any application in C#, the starting point is always to capture all the actors/objects that are interacting with each other. Once we identify the actors, we can then identify the data attributes and methods that each of them must have so that they can exchange the required information with each other.
For the Car example being discussed, the following would be the definition of the Car class. For the sake of explanation, we have just assumed that the attributes will be of type String; however, when we go through Chapter 2, Understanding Classes, Structures, and Interfaces, we will go over some more data types that can be declared in a class. For the car example, the following syntax would be a representative program in a C# application:
class Car{ string Make; string Model; string Color; float Mileage; void StartEngine() { // Implement Start Engine. } void GainSpeed() { // Implement Gain Speed. } void ApplyBrake() { // Implement Gain Speed. } void StopEngine() { // Implement Gain Speed. } }
In any application, there can be some classes that are related to one another. They can be based in terms of similar functionality, or they could be dependent on each other. In C#, we handle such a segregation of functionality via namespaces. For example, we can have a namespace for handling all operations related to reading/writing logs in the file directory. Similarly, we can have namespaces for handling all operations related to capturing user-specified information from inputs.
When our applications continue to evolve and we have several namespaces, we may have a need to group related namespaces under one umbrella. This ensures that if any class changes under any particular namespaces, it will not affect all the classes defined in the application. This structuring of namespace is done via assemblies in C#. Assemblies are also known as DLLs, or dynamically linked libraries. Depending upon how we structure our code, when an application is compiled, it results in multiple DLLs.
Now we will look at how to create a basic program in C#. For the sake of explanation, we will work on the Console Application project:
To create a new project, click on
File
|
New Project
and select
Console App (.NET Framework)
as the project type:
After giving the solution an appropriate name and path, click on OK. Check that the solution has been created. At this point, you should see the Solution Explorer. By default, a .cs file, Program.cs, should be added to the solution. By default, a method by the name of Main will also be added to the class. This method is the first entry point when this application is executed.
Let's open
Program.cs
at this stage. By default, the project will have the following
using
expressions for the following namespaces:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;
A using statement basically signifies that the program can use the classes and methods defined in those namespaces for any execution. In further chapters, we will go over namespaces in detail and learn how to use them.
Now, have a look at the program structure. By default, each class needs to be associated with a namespace. The namespace expression present in the
Program.cs
class indicates the namespace this class is part of:
Each method in C# consists of two parts:
Input parameters
: This is a list of variables that will be passed to the function when it's executed.
Return type
: This is the value that will be returned by the function to the caller when the function finishes its processing.
In the case of the Program function declared previously, the input variable is a collection of arguments. The output variable is void; in other words, it does not return anything. In the forthcoming chapters, we will go over functions in more detail.
Now, let's write a program syntax to execute the famous Hello World output. In a console application, we can do this using Console.Writeline:
The code implementation for this program is as follows:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp1{ class Program { static void Main(string[] args) { Console.WriteLine("Hello World"); } }}
At this stage, we have finished the program and are ready to execute it. Click on
Build
|
Build Solution
. Check that there are no compile time errors
:
At this stage, internally, Visual Studio should have created an
.exe
application for the project:
Open Command Prompt and navigate directly to where the
.exe
file has been created. Execute the
.exe
file and check that the desired output of
Hello World
appears in Command Prompt.
Before we move to the next chapter, let's summarize what we have learned during this chapter. We had a brief recap on the building blocks of C#. We had a walk-through of the .NET Framework architecture and visited the different components in it. We also analyzed what makes C# different from programming languages such as C and C++. We went over the functioning of CLR and how it implements garbage collection in C#. We then wrote our first program, Hello World. By now, you should have a good awareness of what C# is and the features it contains.
