37,19 €
Learn C# in 7 days with practical examples, build a foundation for C# programming, and boost your skills to an advanced level
The book is for aspiring developers and absolute novices who want to get started with the world of programming. You do not need any knowledge of C# for this book.
This book takes a unique approach to teach C# to absolute beginners. You'll learn the basics of the language in seven days. It takes a practical approach to explain the important concepts that build the foundation of the C# programming language.
The book begins by teaching you the basic fundamentals using real-world practical examples and gets you acquainted with C# programming. We cover some important features and nuances of the language in a hands-on way, helping you grasp the concepts in a fluid manner.
Later, you'll explore the concepts of Object-Oriented Programming (OOP) through a real-world example. Then we dive into advanced-level concepts such as generics and collections, and you'll get acquainted with objects and LINQ. Towards the end, you'll build an application that covers all the concepts explained in the book.
By the end of this book, you will have next-level skills and a good knowledge of the fundamentals of C#.
Fast paced guide to get you up-to-speed with the language. Every chapter is followed by an exercise that focuses on building something with the language. The codes of the exercises can be found on the Packt website
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 266
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
First published: October 2017
Production reference: 1041017
ISBN 978-1-78728-704-4
www.packtpub.com
Author
Gaurav Aroraa
Copy Editor
Muktikant Garimella
Reviewer
Shivprasad Koirala
Project Coordinator
Ulhas Kambali
Commissioning Editor
Aaron Lazar
Proofreader
Safis Editing
Acquisition Editor
Denim Pinto
Indexer
Tejal Daruwale Soni
ContentDevelopmentEditor
Vikas Tiwari
Graphics
Tania Dutta
Technical Editor
Diwakar Shukla
Production Coordinator
Nilesh Mohite
Gaurav Aroraa has an M.Phil in computer science. He is a Microsoft MVP, certified as a scrum trainer/coach, XEN for ITIL-F, and APMG for PRINCE-F and PRINCE-P. Gaurav serves as a mentor at IndiaMentor and the webmaster of dotnetspider. He is also a contributor to TechNet Wiki and a cofounder of Innatus Curo Software LLC. In the 19+ years of his career, he has mentored thousands of students and industry professionals. You can reach Gaurav via his blog, LinkedIn, or Twitter (@g_arora).
Shivprasad Koirala is an X-Microsoft MVP, Microsoft trainer, and technical author. He has written more than 80 books, and some of his bestsellers include .NET interview questions and SQL Server interview questions. You can catch him mostly recording training videos at http://www.questpond.com.
For support files and downloads related to your book, please visit www.PacktPub.com. 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.PacktPub.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.PacktPub.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.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at "Amazon Book URL". If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
Day 01 - Overview of the .NET Framework
What is programming?
What is .NET?
What is .NET Core?
.NET Core features
What makes .NET Core?
What is .NET Standard?
Available IDEs and editors for C#
Setting up the environment
Hands - on exercises
Revisiting Day 01
Day 02 - Getting Started with C#
Introduction to C#
History of the C# language
Understanding a typical C# program
1 (System)
3 (Day02)
2 (Program)
4 (Main)
5 (Day02)
6 (Day02)
7 (Dependencies)
8 (Program.cs)
Deep-dive into application using Visual Studio
Discussing code
Color
Beep
An overview of C# reserved keywords, types, and operators
Identifiers
Contextual
Types
Value type
Data types
Reference type
Pointer type
Null type
Operators
Discussing operator precedence in C#
Operator overloading
An overview of type conversion
Implicit conversion
Explicit conversion
Understanding statements
Declarative statement
Expression statement
Selection statement
The if statement
The if..else statement
if...else if...else statement
Nested if statement
Switch statement
Iteration statement
The do...while loop
The while loop
The for loop
The foreach loop
The jump statement
break
continue
default
Exception-handling statement
Arrays and string manipulations
Arrays
Types of arrays
Single-dimensional array
Multidimensional array
Jagged array
Strings
Structure versus class
Hands-on exercise
Revisiting day 2
Day 03 - What's New in C#
Tuples and deconstruction
Tuples
The System.ValueTuple struct
Deconstruction
Tuple – important points to remember
Pattern matching
is expression
switch statement
constant pattern
type pattern
When clause in case expression
Local functions
Literal improvements
Binary literals
Digit separator
Async Main
Restrictions while using new signatures
Default expressions
Member variables
Constants
Infer tuple names
Other features supposed to release
Pattern-matching with generics
Reference assemblies
Hands-on exercises
Revisiting Day 03
Day 04 - Discussing C# Class Members
Modifiers
Access modifiers and accessibility levels
public
protected
internal
composite
private
Rules for the access modifier
abstract
Rules of the abstract modifier
async
const
event
extern
new
override
partial
readonly
sealed
static
Rules for the static modifier
unsafe
virtual
Methods
How to use a method?
Properties
Types of properties
Read-write property
Read-only property
Computed property
Block-bodied members
Expression-bodied members
Property using validation
Indexers
File I/O
FileStream
Exception handling
try block
catch block
finally block
Different compiler-generated exceptions in catch block
User-defined exceptions
Discussing a regular expression and its importance
The Importance of a regular expression
Flexible
Constructs
Special characters
The period sign (.)
The word sign (w)
The space sign (s)
The digit sign (d)
The hyphen sign (-)
Specifying the number of matches
Hands-on exercise
Revisiting Day 04
Day 05 - Overview of Reflection and Collections
What is reflection?
Reflection in use
Getting type info
Overview of delegates and events
Delegates
Declaring a delegate type
Instances of delegate
Delegates in use
Events
Declaring an event
Collections and non-generics
ArrayList
Declaration of ArrayList
Properties
Methods
HashTable
Declaration of HashTable
Properties
Methods
SortedList
Declaration of SortedList
Properties
Methods
Stack
Declaration of Stack
Properties
Methods
Queue
Declaration of Queue
Properties
Methods
BitArray
Hands - on exercise
Revisiting Day 05
Day 06 - Deep Dive with Advanced Concepts
Playing with collections and generics
Understanding collection classes and their usage
Performance - BitArray versus boolArray
Understanding generics and their usage
Collections and generics
Why should we use generics?
Discussing constraints
The value type
The reference type
The default constructor
The base class constraint
The interface constraint
Beautifying code using attributes
Types of attributes
AttributeUsage
Obsolete
Conditional
Creating and implementing a custom attribute
Prerequisites
Leveraging preprocessor directives
Important points
Preprocessor directives in action
Getting started with LINQ
Writing unsafe code
Writing asynchronous code
Hands-on exercises
Revisiting Day 6
Day 07 - Understanding Object-Oriented Programming with C#
Introduction to OOP
Discussing Object relations
Inheritance
Understanding inheritance
Types of inheritance
Member visibility in inheritance
Implementing inheritance
Implementing multiple inheritance in C#
Abstraction
Implementing abstraction
Abstract class
Features of abstract class
Interface
Features of interface
Encapsulation
What are access modifier in C#?
Implementing encapsulation
Polymorphism
Types of polymorphism
Implementing polymorphism
Hands on Exercise
Revisiting Day 7
What next?
Day 08 - Test Your Skills – Build a Real-World Application
Why are we developing this application?
Getting started with application development
Prerequisites
The database design
Overview
Discussing the basic architecture
Revisiting day 08
Learning a new language or switching to an entirely different technology is a common industry demand. As a student one should prepare oneself to be up to date with market trends, and as a professional, one should be aware of the new things that are coming in with new technologies. To meet this demand, there are a lot of books that are of thousand pages long and aim to be comprehensive references to the C# programming language. This book is entirely different and written so that someone who has a very basic knowledge of the C# language, or is a professional and working with another language but wants to switch, can learn C#. This book was designed with the aim that one should start with the basics and progress to an advanced level. The book contains concise content with relevant examples to explain everything. There are a lot of sections in the book that will encourage you to learn more ; with this knowledge, you can impress your colleagues, employers, or batch-mates. There will be a few terms you will hear first time – no problem, you can learn about them in this book. At the end of every section you will find a hands-on exercise section that will build confidence and give you ideas for solving practical problems. You can find various hints in these exercises. For the code examples, you can go to the GitHub repository (https://github.com/PacktPublishing/Learn-CSharp-in-7-days/) and download the source code for all chapters. You can easily use these code example in Visual Studio 2017 Update 3 by following the instructions mentioned thereon.
Chapter 1, Day 01 - Overview of the .NET Framework, gets you familiar with C#, including .NET Framework and .NET Core.
Chapter 2, Day 02 - Getting Started with C#, gives you a basic understanding of C# by iterating through the type system and the use of various constructs. The use and importance of reserved keywords, understanding statements, type conversions.
Chapter 3, Day 03 - What's New in C#, gets you familiar with various new important features introduced in versions 7.0 and 7.1.
Chapter 4, Day 04 - Discussing C# Class Members, explains the fundamentals of class and its members will be explained including indexers, the filesystem, exception handling, and string manipulation with regular expressions.
Chapter 5, Day 05 - Overview of Reflection and Collections, covers working with code using reflection, and an introduction to collections, delegates, and events.
Chapter 6, Day 06 - Deep Dive with Advanced Concepts, teaches you about implementing attributes, using preprocessors, and understanding generics and their usage, including sync and async programming.
Chapter 7, Day 07 - Understanding Object-Oriented Programming withC#, In this chapter we will learn all 4-paradigm of oop and implement using C# 7.0.
Chapter 8, Day 08 - Test Your Skills – Build a Real-World Application, helps you to write a complete application with the help of what you learned from this book.
All supporting code samples in this book have been tested on .NET Core 2.0 using Visual Studio 2017 update 3, database using SQL Server 2008R2 or later on the Windows platform.
Learn C# in 7 Days is a fast-paced guide. In this book, we take a unique approach to teaching C# to an absolute beginner, who will be able to learn the basics of the language in seven days. This practical book comes with important concepts that introduce the foundation of the C# programming language. This book addresses the challenges and issues that most beginners face. It covers issues such as the need to learn C#, issues with setting up a development environment with C#, challenges such as mathematical operations, and other day-to-day problems. Its fast-paced writing style allows the reader to get up and running in no time. We begin with the absolute basics in the first chapter (variables, syntax, control flows, and so on), and then move on to concepts such as statements, arrays, string processing, methods, inheritance, I/O handling, and so on. Every chapter is followed by an exercise that focuses on building something with the language. This book is a fast-paced guide to get readers upto speed with the language. It works as a reference guide, describing the major features of C#. Readers will be able to build easy and simple code with real-world scenarios. By the end of this book, you will be able to take your skills to the next level, with a good knowledge of the fundamentals of C#.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://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 to our website using your email address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
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/Learn-CSharp-in-7-Days. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
This is Day 01 of our seven day journey to learn C#. Today, we will begin with an introduction of a new world of programming and will discuss all the basic concepts required to learn this programming language. We will also discuss the .NET Framework and the .NET Core framework by covering important concepts of the framework. We will also get a basic understanding of managed and unmanaged code. At the end of the day, we will start with a simple Hello World program.
Today, we will learn the following topics:
What is programming?
What is .NET Core?
What is .NET standard?
While we are referring to .NET (pronounced as dot NET), it is .NET Full, as we have .NET Core in place and we are using .NET Core in our book examples with C# 7.0 as the language. Before moving ahead, you should know about .NET because there is a .NET Standard available with the .NET Core, that is API servers for both .NET Framework as well .NET Core. So, if you created a project using .NET Standard it is valid for both .NET Framework and .NET Core.
.NET is nothing but a combination of languages, runtime, and libraries, by using which we can develop managed software/applications. The software written in .NET is managed or is in a managed environment. To understand managed, we need to dig into how binary executables are available for operating systems. This comprises three broader steps:
Writing the code (source code).
Compiler compiles the source code.
The operating system executes the binary executable immediately:
The preceding process is a standard process depicting how compilers compile the source code and create executable binaries, but in the case of .NET, the compiler (C# compiler for our code) does not directly provide a binary executable; it provides an assembly and this assembly consists of metadata and intermediate language code, also known as Microsoft Intermediate Language (MSIL) or Intermediate Language (IL). This MSIL is a high-level language and this can’t be understood directly by the machine, as MSIL is not machine-specific code or byte code. For proper execution, it should be interpreted. This interpretation from MSIL or IL to the machine language happens with the help of JIT. In other words, JIT compiles MSIL, IL into the machine language, also called native code. For more information, refer to https://msdn.microsoft.com/en-us/library/ht8ecch6(v=vs.90).aspx.
For 64-bit compilation, Microsoft has announced RyuJIT (https://blogs.msdn.microsoft.com/dotnet/2014/02/27/ryujit-ctp2-getting-ready-for-prime-time/). In the coming versions, 32-bit compilation will also be handled by RyuJIT (https://github.com/dotnet/announcements/issues/10). After this, we can now have a single code base for both CoreCLR.
Intermediate language is a high-level component-based assembly language.
In our seven days of learning, we will not focus on the framework, but we will be more focused on the C# language with the use of .NET Core. In the coming sections, we will discuss important things of .NET Core in such a way that while we work with a C# program, we should understand how our program talks with the operating system.
.NET Core is a new general-purpose development environment introduced by Microsoft to meet cross-platform requirements. .NET Core supports Windows, Linux, and OSX.
.NET Core is an open source software development framework released under MIT License and maintained by the Microsoft and .NET community on the GitHub (https://github.com/dotnet/core) repository.
Here are some important features of .NET Core, that make .NET Core an important evolution step in software development:
Cross-platform
: Currently, .NET Core can be run on Windows, Linux, and macOS; in the future, there may be more. Refer to the roadmap (
https://github.com/dotnet/core/blob/master/roadmap.md
) for more info.
Having easy command-line tools
: You can use command-line tools for exercise with .NET Core. Refer to CLI tools for more at
https://docs.microsoft.com/en-us/dotnet/articles/core/tools/index
.
Having compatibility
: With the use of the .NET standard library, .NET Core is compatible with the .NET Frameworks, Xamarin and Mono.
Open source
: .NET Core platform is released under MIT License and is a .NET Foundation project (
https://dotnetfoundation.org/
).
.NET Core is a combination of coreclr, corefx, and cli and roslyn. These are the main components of .NET Core composition.
Coreclr
: It is a .NET runtime and provides assembly loading, garbage collector, and many more. You can check coreclr for more info at
https://github.com/dotnet/coreclr
.
Corefx
: It is a framework library; you can check corefx for more info at
https://github.com/dotnet/corefx
.
Cli
: It is nothing but a command-line interface tool and roslyn is the language compiler (the C# language in our case). Refer to cli (
https://github.com/dotnet/cli
) and Roslyn for more info at
https://github.com/dotnet/roslyn
.
The .NET Standard is a set of APIs that resolves the problems of code sharing while you’re trying to write cross-platform applications. Currently, Microsoft is working on .NET Standard 2.0 to make it streamlined, and these standards will be implemented by all, that is, .NET Framework, .NET Core, and Xamarin. With the use of .NET Standard (that is a set of APIs), you are ensuring that your program and class library will be available for all targeted .NET Frameworks and .NET Core. In other words, .NET Standard will replace Portable Class Libraries(PCL). For more information, refer to https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/.
The .NET Standard 2.0 repository is available at https://github.com/dotnet/standard.
Till now, you've got an idea of .NET Core and a few other things that help build cross-platform applications. In the coming sections, we will prepare the environment in order to start learning the C# language using Visual Studio 2017 (preferably the community edition).
Integrated Development Environment (IDE) is nothing but software facilitating the development of applications. On the other hand, editors are basically meant to add/update predefined or new content. When we talk about the C# editor, we are referring to an editor that helps write C# programs. Some editors come with a lot of add-ons or plugins and can compile or run the programs.
We will use Visual Studio 2017 as our preferred C# IDE; however, there are a few more C# IDEs and editors you can go with:
Visual Studio Code:
VS Code is an editor, and you can start by downloading it from
https://code.visualstudio.com/
. To start with VS Code, you need to install the C# extension from
https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp
.
Cloud9:
It is a web browser-based IDE. You can start it for free by signing up at
https://c9.io/signup
.
JetBrain Rider:
This is a cross-platform IDE by JetBrains. For more information, visit
https://www.jetbrains.com/rider/
.
Zeus IDE:
This is an IDE designed for the Windows platform. You can start using Zeus from
https://www.zeusedit.com/index.html
.
Text editor:
This is the way you can go without any installation; just use a text editor of your choice. I use Notepad++ (
https://notepad-plus-plus.org/download/v7.3.3.html
) and the C
ommand Line Interface
(
CLI
) to build code. Refer to
https://docs.microsoft.com/en-us/dotnet/articles/core/tools/
to know more about how to start with the CLI.
There may be more alternative IDEs and editors, but they are not as important to us.
In this section, we will see step by step how to initiate the installation of Visual Studio 2017 (preferably, the community edition) on Windows 10:
Go to
https://www.visualstudio.com/downloads/
(you can also get the benefits of Dev Essentials from
https://www.visualstudio.com/dev-essentials/
).
Download
Visual Studio Community
(https
://www.visualstudio.com/thank-you-downloading-visual-studio/?sku=Community&rel=15
):
Start the Visual Studio setup.
From
Workloads
, select the options you want to install. For our book, we need
.NET desktop development
and .NET Core:
Click on
Install
to start the installation:
Click
Launch
once the installation is completed.
Sign up for Visual Studio using your Live ID.
Select
Visual C#
as your development setting.
You will see the start page as follows:
We are all set to start with our first step.
Answer the following questions by covering the concepts of today’s learning.
What is programming? Write down an algorithm to find out vowel counts from all the pages of book,
Learn C# in 7-days
.
What is .NET Core and .NET Standard?
What makes a .NET Core an evolutional software ?
Today, we walked you through some important concepts of .NET Core and .NET Standard. You learned what programs and algorithms are in the programming world.