1 By Joe Mayo Foreword by Daniel Jebaraj 2 Copyright © 2015 by Syncfusion, Inc. 2501 Aerial Center Parkway Suite 200 Morrisville, NC 27560 USA All rights reserved. I mportant licensing information. Please read. This book is available for free download from www.syncfusion.com on completion of a registration form. If you obtained this book from any other source, please register and download a free copy from www.syncfusion.com. This book is licensed for reading only if obtained from www.syncfusion.com. This book is licensed strictly for personal or educational use. Redistribution in any form is prohibited. The authors and copyright holders provide absolutely no warranty for any information provided. The authors and copyright holders shall not be liable for any claim, damages, or any other liability arising from, out of, or in connection with the information in this book. Please do not use this book if the listed terms are unacceptable. Use shall constitute acceptance of the terms listed. SYNCFUSION, SUCCINCTLY, DELIVER INNOVATION WITH EASE, ESSENTIAL, and .NET ESSENTIALS are the registered trademarks of Syncfusion, Inc. Technical Reviewer: Stephen Haunts Copy Editor: Ben Ball Acquisitions Coordinator: Hillary Bowling, marketing coordinator, Syncfusion, Inc. Proofreader: Graham High, content producer, Syncfusion, Inc. 3 Table of Contents The Story behind the Succinctly Series of Books ................................................................................... 7 About the Author ......................................................................................................................................... 9 Chapter 1 Introducing C# and .NET ....................................................................................................... 10 What can I do with C#? .......................................................................................................................... 10 What is .NET? ........................................................................................................................................ 10 Writing, Running, and Deploying a C# Program .................................................................................... 11 Starting a New Program ................................................................................................................... 11 Namespaces and Code Organization .................................................................................................... 12 Running the Program ........................................................................................................................ 14 Deploying the Program ..................................................................................................................... 15 Summary ................................................................................................................................................ 16 Chapter 2 Coding Expressions and Statements ................................................................................... 17 Writing Simple Statements..................................................................................................................... 17 Overview of C# Types and Operators ................................................................................................... 18 Operator Precedence and Associativity ................................................................................................. 22 Formatting Strings .................................................................................................................................. 22 Branching Statements ............................................................................................................................ 23 Arrays and Collections ........................................................................................................................... 25 Looping Statements ............................................................................................................................... 26 Wrapping Up .......................................................................................................................................... 28 Summary ................................................................................................................................................ 30 Chapter 3 Methods and Properties ........................................................................................................ 31 Starting at Main ...................................................................................................................................... 31 Modularizing with Methods .................................................................................................................... 31 4 Simplifying Code with Methods .............................................................................................................. 34 Adding Properties .................................................................................................................................. 34 Exception Handling ................................................................................................................................ 37 Summary ................................................................................................................................................ 41 Chapter 4 Writing Object-Oriented Code ............................................................................................... 42 Implementing Inheritance....................................................................................................................... 42 Access Modifiers and Encapsulation ..................................................................................................... 44 Designing Types: Class vs. Struct ......................................................................................................... 44 Creating Enums ..................................................................................................................................... 48 Enabling Polymorphism ......................................................................................................................... 49 Writing Abstract Classes ........................................................................................................................ 53 Exposing Interfaces ............................................................................................................................... 54 Object Lifetime ....................................................................................................................................... 56 Summary ................................................................................................................................................ 61 Chapter 5 Handling Delegates, Events, and Lambdas ......................................................................... 62 Referencing Methods with Delegates .................................................................................................... 62 Firing Events .......................................................................................................................................... 63 Working with Lambdas ........................................................................................................................... 65 More FCL Delegate Types ..................................................................................................................... 68 Expression-Bodied Members ................................................................................................................. 69 Summary ................................................................................................................................................ 70 Chapter 6 Working with Collections and Generics .............................................................................. 71 Using Collections ................................................................................................................................... 71 Writing Generic Code ............................................................................................................................. 74 Summary ................................................................................................................................................ 79 Chapter 7 Querying Objects with LINQ .................................................................................................. 80 Getting Started ....................................................................................................................................... 80 5 Querying Collections .............................................................................................................................. 81 Filtering Data .......................................................................................................................................... 83 Ordering Collections .............................................................................................................................. 84 Joining Objects ...................................................................................................................................... 84 Using Standard Operators ..................................................................................................................... 85 Summary ................................................................................................................................................ 88 Chapter 8 Making Your Code Asynchronous........................................................................................ 89 Consuming Async Code ........................................................................................................................ 89 Async Return Types ............................................................................................................................... 91 Developing Async Libraries ................................................................................................................... 92 Understanding What Thread the Code is Running On ..................................................................... 92 Fulfilling the Async Contract ............................................................................................................. 94 A Few More Notes on Async ................................................................................................................. 95 Summary ................................................................................................................................................ 95 Chapter 9 Moving Forward and More Things to Know ........................................................................ 96 Decorating Code with Attributes ............................................................................................................ 96 Using Reflection ..................................................................................................................................... 97 Working with Code Dynamically ............................................................................................................ 98 Summary .............................................................................................................................................. 100 6 The Story behind the Succinctly Series of Books Daniel Jebaraj, Vice President Syncfusion, Inc. St aying on the cutting edge As many of you may know, Syncfusion is a provider of software components for the Microsoft platform. This puts us in the exciting but challenging position of always being on the cutting edge. Whenever platforms or tools are shipping out of Microsoft, which seems to be about every other week these days, we have to educate ourselves, quickly. Information is plentiful but harder to digest In reality, this translates into a lot of book orders, blog searches, and Twitter scans. While more information is becoming available on the Internet and more and more books are being published, even on topics that are relatively new, one aspect that continues to inhibit us is the inability to find concise technology overview books. We are usually faced with two options: read several 500+ page books or scour the web for relevant blog posts and other articles. Just as everyone else who has a job to do and customers to serve, we find this quite frustrating. The Succinctly series This frustration translated into a deep desire to produce a series of concise technical books that would be targeted at developers working on the Microsoft platform. We firmly believe, given the background knowledge such developers have, that most topics can be translated into books that are between 50 and 100 pages. This is exactly what we resolved to accomplish with the Succinctly series. Isn’t everything wonderful born out of a deep desire to change things for the better? The best authors, the best content Each author was carefully chosen from a pool of talented experts who shared our vision. The book you now hold in your hands, and the others available in this series, are a result of the authors’ tireless work. You will find original content that is guaranteed to get you up and running in about the time it takes to drink a few cups of coffee. 7 Free forever Syncfusion will be working to produce books on several topics. The books will always be free. Any updates we publish will also be free. Free? What is the catch? There is no catch here. Syncfusion has a vested interest in this effort. As a component vendor, our unique claim has always been that we offer deeper and broader frameworks than anyone else on the market. Developer education greatly helps us market and sell against competing vendors who promise to “enable AJAX support with one click,” or “turn the moon to cheese!” Let us know what you think If you have any topics of interest, thoughts, or feedback, please feel free to send them to us at [email protected]. We sincerely hope you enjoy reading this book and that it helps you better understand the topic of study. Thank you for reading. Please follow us on Twitter and “Like” us on Facebook to help us spread the word about the Succinctly series! 8 About the Author Joe Mayo is an author, a consultant at Mayo Software, LLC, and an instructor who specializes in Microsoft .NET technology. Joe has written several books, including C# Unleashed (Sams) and LINQ Programming (McGraw-Hill), and coauthored ASP.NET 2.0 MVP Hacks and Tips (Wrox). His articles have been published in CODE Magazine and the online publications Inform IT and C# Station. Joe is a regular presenter on .NET topics and has received multiple Microsoft Visual C# MVP awards. His open source project, LINQ to Twitter, is hosted on GitHub, and you can read his blog at Geeks with Blogs. You can find Joe on Twitter as @JoeMayo. 9 Chapter 1 Introducing C# and .NET Welcome to C# Succinctly. True to the Succinctly series concept, this book is very focused on a single topic: the C# programming language. I might briefly mention some technologies that you can write with C# or explain how a feature fits into those technologies, but the whole of this book is about helping you become familiar with C# syntax. In this chapter, I’ll start with some introductory information and then jump straight into a simple C# program. What can I do with C#? C# is a general purpose, object-oriented, component-based programming language. As a general purpose language, you have a number of ways to apply C# to accomplish many different tasks. You can build web applications with ASP.NET, desktop applications with Windows Presentation Foundation (WPF), or build mobile applications for Windows Phone. Other applications include code that runs in the cloud via Windows Azure, and iOS, Android, and Windows Phone support with the Xamarin platform. There might be times when you need a different language, like C or C++, to communicate with hardware or real-time systems. However, from a general programming perspective, you can do a lot with C#. What is .NET? .NET is a platform that includes languages, a runtime, and framework libraries, allowing developers to create many types of applications. C# is one of the .NET languages, which also includes Visual Basic, F#, C++, and more. The runtime is more formally named the Common Language Runtime (CLR). Programming languages that target the CLR compile to an Intermediate Language (IL). The CLR itself is a virtual machine that runs IL and provides many services such as memory management, garbage collection, exception management, security, and more. The Framework Class Library (FCL) is a set of reusable code that provides both general services and technology-specific platforms. The general services include essential types such as collections, cryptography, networking, and more. In addition to general classes, the FCL includes technology-specific platforms like ASP.NET, WPF, web services, and more. The value the FCL offers is to have common components available for reuse, saving time and money without needing to write that code yourself. There’s a huge ecosystem of open-source and commercial software that relies on and supports .NET. If you visit CodePlex, GitHub, or any other open-source code repository site, you’ll see a multitude of projects written in C#. Commercial offerings include tools and services that help you build code, manage systems, and offer applications. Syncfusion is part of this ecosystem, offering reusable components for many of the .NET technologies I have mentioned. 10