Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Professional C# 6 and .NET Core 1.0
Professional C# 6 and .NET Core 1.0
Professional C# 6 and .NET Core 1.0
Ebook3,491 pages74 hours

Professional C# 6 and .NET Core 1.0

Rating: 5 out of 5 stars

5/5

()

Read preview

About this ebook

A true professional's guide to C# 6

Professional C# 6 and .NET Core 1.0 provides complete coverage of the latest updates, features, and capabilities, giving you everything you need for C#. Get expert instruction on the latest changes to Visual Studio 2015, Windows Runtime, ADO.NET, ASP.NET, Windows Store Apps, Windows Workflow Foundation, and more, with clear explanations, no-nonsense pacing, and valuable expert insight. This incredibly useful guide serves as both tutorial and desk reference, providing a professional-level review of C# architecture and its application in a number of areas. You'll gain a solid background in managed code and .NET constructs within the context of the 2015 release, so you can get acclimated quickly and get back to work.

The new updates can actively streamline your workflow, with major changes including reimagined C# refactoring support, a new .NET Web app stack, and the .NET compiler platform that makes C# and Visual Basic compilers available as APIs. This book walks you through the changes with a comprehensive C# review.

  • Explore the new Visual Studio templates for ASP.NET Core 1.0, Web Forms, and MVC
  • Learn about the networking switch to HttpClient and ASP.NET Web API's replacement of WCF Data Services
  • Work with the latest updates to the event log, Windows Runtime 2.0, and Windows 8.1 deployment and localization
  • Dig deep into the new .NET 5.0 GC behaviors and the Migrations addition to ADO.NET

Microsoft has stepped up both the cadence and magnitude of their software releases. Professional C# 6 and .NET Core 1.0 shows you everything you need to know about working with C# in a real-world context.

LanguageEnglish
PublisherWiley
Release dateApr 1, 2016
ISBN9781119096634
Professional C# 6 and .NET Core 1.0

Read more from Christian Nagel

Related to Professional C# 6 and .NET Core 1.0

Related ebooks

Programming For You

View More

Related articles

Reviews for Professional C# 6 and .NET Core 1.0

Rating: 5 out of 5 stars
5/5

1 rating0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Professional C# 6 and .NET Core 1.0 - Christian Nagel

    Introduction

    IF YOU WERE TO DESCRIBE THE C# LANGUAGE and .NET as the most significant technology for developers available, you would not be exaggerating. .NET is designed to provide an environment within which you can develop almost any application to run on Windows. Runs on Windows—wait, I would have said that with previous versions of the .NET Framework. The new version, .NET Core 1.0 not only runs on Windows, but it also runs on Linux and Mac systems. The C# programming language is designed specifically to work with .NET. By using C#, you can, for example, write a web page, a Windows Presentation Foundation (WPF) application, a REST web service, a component of a distributed application, a database access component, a classic Windows desktop application, or even a Universal Windows Platform (UWP) app that enables online and offline capabilities. This book covers .NET Core 1.0 and also the full .NET Framework stack, .NET Framework 4.6. If you code using any of the prior versions, there may be sections of the book that will not work for you.

    Where possible, samples of this book make use of .NET Core 1.0. The book code is built on a Windows system, but you can run the samples on other platforms as well; small changes might be needed to run them on Linux. Read Chapter 1, .NET Application Architectures, to see how to build the applications for the Linux platform. What’s not possible to run on Linux? WPF applications still need the full .NET Framework and run only on Windows. UWP apps are using .NET Core, but also require the Windows Runtime. These apps require Windows as well. These UI technologies are covered in Part III of the book, Core Apps.

    So what’s the big deal about .NET and C#?

    The Significance of .NET Core

    To understand the significance of .NET Core, you must consider the long-lived .NET Framework. The .NET Framework 1.0 was released in the year 2002. Since then about every two years a new major release has been made available. With Visual Studio 2013 we had C# 5 and .NET 4.5. The .NET Framework 4.5 is huge, with more than 20,000 classes.

    NOTE Get into more details of the releases of the .NET Framework and C# in Chapter 1.

    What are the problems with this huge framework? How is this solved with .NET Core?

    For new developers, getting into this huge framework is not easy. Many things exist that are important for legacy applications, but they’re not really important for new applications. For experienced developers it’s not that easy to decide between these technologies to select the best one. You have to decide between ASP.NET Web Forms and ASP.NET MVC for web applications, decide between Windows Forms and WPF or the Universal Windows Platform for client applications, decide between the Entity Framework and LINQ to SQL for data access, decide between ArrayList and List for storing collections. . . . For some experienced developers the choice is obvious; for most it’s not that easy. It’s even more difficult for developers just starting with .NET.

    .NET Core is based on smaller units, small NuGet packages. The Console class is only needed with console applications. With the .NET Framework, the Console class is available with mscorlib, an assembly that’s referenced by every .NET application. Using .NET Core, you have to explicitly decide to use the System.Console NuGet package. Otherwise, the Console class is not available.

    Smaller packages also allow you to get rid of parts of the framework more easily. In case you need older collection classes for legacy applications, they are available with the NuGet package System.Collections.NonGeneric. With new applications you can define a list of packages that can be used, and System.Collections.NonGeneric can be excluded from this list.

    Nowadays, development is going a lot faster. With many products, customers receive ongoing updates of products instead of receiving new versions every 2 years. Even Windows, with Windows 10, is on this fast pace. Customers receive smaller features with each update, but they receive them at a faster pace. Having 2-year release cycles with the .NET Framework nowadays is not fast enough. Some technologies, like the Entity Framework, already circumvented the problem by offering new features via NuGet packages that can be released independently of the .NET Framework.

    Updating smaller pieces allows for faster innovation. .NET Core, which is based on many small NuGet packages, can be changed more easily. .NET Core and ASP.NET are now open source. You can find the source code for .NET Core at http://www.github.com/dotnet and for ASP.NET at http://www.github.com/aspnet.

    When .NET was released, Windows had a big market share both on the client and on the server. Now the world is more fragmented. Companies decided against running server-side code with ASP.NET because it didn’t run on Linux. ASP.NET Core 1.0 with .NET Core can run on Linux.

    .NET Core is platform-independent and supports Windows, Linux, and Mac systems. For client applications, you can use .NET with Xamarin on iPhone and Android.

    The .NET Framework required having the same version of the .NET runtime that was used during development to be installed on the target system. Many application developments have been restricted by the version of the .NET Framework to use based on client needs. This is not only an issue for client-based application development but also for the server. I had to switch back to older .NET runtime versions because my provider didn’t support the newest one. With .NET Core, the runtime is delivered with the application.

    When ASP.NET was built, compatibility with the predecessor technology Active Server Pages (ASP) that was built with JavaScript or VBScript code running on the server was an important aspect. Nowadays this is not needed anymore. ASP.NET Web Forms was built with the idea that the developer doesn’t need to know anything about JavaScript and HTML, and everything could be done with server-side code. Now, because of the huge number of JavaScript frameworks and enhancements in HTML, more control on JavaScript and HTML is needed.

    With the new version of ASP.NET, performance has a big role in the framework architecture. You only have performance impacts for the things you really need. In case you don’t have static files with your web application, you have to explicitly decide on using it, otherwise you don’t pay a performance impact for this. With fine-grained control you can decide what features you need.

    To get an even bigger performance improvement, .NET Core can be built to native code. This is possible not only on Windows but also on Linux and Mac systems. With this you can get performance improvement especially on program startup, and you use less memory.

    Now there’s an issue with legacy applications. Most applications can’t switch that easily to .NET Core. The full .NET Framework—running just on Windows—is evolving as well. It’s not evolving in such big steps as .NET Core, but it is a mature framework. At the time of this writing, .NET 4.6.1 is released, with small updates compared to the previous versions. Applications that have been written with Windows Forms or ASP.NET Web Forms still need to use the full framework, but they can take advantage of the enhancements of .NET 4.6.1. Using .NET 4.6.1, you can also use NuGet packages built for .NET Core. Many new NuGet packages are built in a portable manner. With ASP.NET MVC 5 web applications you can also decide to change to ASP.NET MVC 6 running on ASP.NET Core 1.0. ASP.NET Core 1.0 allows using either .NET Core or .NET 4.6. This can make the switch easier. However, for running ASP.NET MVC on Linux, you need to migrate the ASP.NET MVC application to use .NET Core, but running on Linux wasn’t available previously as well.

    Here’s a summary of some of the features of .NET Core:

    .NET Core is open source.

    Smaller NuGet packages allow for faster innovation.

    .NET Core supports multiple platforms.

    .NET Core can compile to native code.

    ASP.NET can run on Windows and Linux.

    Existing applications still run and can evolve into the future.

    As you can see with the features of .NET Core, this technology made the biggest change for .NET in the history since the first version of .NET. This is a new start. From here we can continue our journey on new developments in a fast pace.

    The Significance of C#

    When C# was released in the year 2002, it was a language developed for the .NET Framework. C# was designed with ideas from C++, Java, and Pascal. Anders Hejlsberg had come to Microsoft from Borland and brought experience with language development of Delphi. At Microsoft, Hejlsberg worked on Microsoft’s version of Java, named J++, before creating C#.

    C# started not only as an object-oriented general purpose programming language but was a component-based programming language that supported properties, events, attributes (annotations), and building assemblies (binaries including metadata).

    Over time, C# was enhanced with generics, Language Integrated Query (LINQ), lambda expressions, dynamic features, and easier asynchronous programming. C# is not an easy programming language because of the many features it offers, but it’s continuously evolving with features that are practical to use. With this, C# is more than an object-oriented or component-based language; it also includes ideas of functional programming—things that are of practical use for a general-purpose language developing all kind of applications.

    What’s New in C# 6

    With C# 6 a new C# compiler is available. It’s not only that a source code cleanup was done; the features of the compiler pipeline can now be used from custom programs, and are used by many features of Visual Studio.

    This new compiler platform made it possible to enhance C# with many new features. Although there’s not a feature with such an impact as LINQ or the async keyword, the many enhancements increase developer productivity. What are the changes of C# 6?

    static using

    The static using declaration allows invoking static methods without the class name:

    In C# 5

    using System;

    // etc.

    Console.WriteLine(Hello, World!);

    In C# 6

    using static

    System.Console;

    // etc.

    WriteLine(Hello, World);

    The using static keyword is covered in Chapter 2, Core C#.

    Expression-Bodied Methods

    With expression-bodied methods, a method that includes just one statement can be written with the lambda syntax:

    In C# 5

    public bool IsSquare(Rectangle rect)

    {

      return rect.Height == rect.Width;

    }

    In C# 6

    public bool IsSquare(Rectangle rect)

    => rect.Height == rect.Width;

    Expression-bodied methods are covered in Chapter 3, Objects and Types.

    Expression-Bodied Properties

    Similar to expression-bodied methods, one-line properties with only a get accessor can be written with the lambda syntax:

    In C# 5

    public string FullName

    {

      get

      {

        return FirstName + + LastName;

      }

    }

    In C# 6

    public string FullName => FirstName + + LastName;

    Expression-bodied properties are covered in Chapter 3.

    Auto-Implemented Property Intializers

    Auto-implemented properties can be initialized with a property initializer:

    In C# 5

    public class Person

    {

      public Person()

      {

        Age = 24;

      }

      public int Age {get; set;}

    }

    In C# 6

    public class Person

    {

      public int Age {get; set;} = 42;

     

    }

    Auto-implemented property initializers are covered in Chapter 3.

    Read-Only Auto Properties

    To implement read-only properties, C# 5 requires the full property syntax. With C# 6, you can do this using auto-implemented properties:

    In C# 5

    private readonly int _bookId;

    public BookId

    {

      get

      {

        return _bookId;

      }

    }

    In C# 6

    public BookId {get;}

    Read-only auto properties are covered in Chapter 3.

    nameof Operator

    With the new nameof operator, names of fields, properties, methods, or types can be accessed. With this, name changes are not missed with refactoring:

    In C# 5

    public void Method(object o)

    {

      if (o == null) throw new ArgumentNullException(o);

    In C# 6

    public void Method(object o)

    {

      if (o == null) throw new ArgumentNullException(

    nameof(o));

    The nameof operator is covered in Chapter 8, Operators and Casts.

    Null Propagation Operator

    The null propagation operator simplifies null checks:

    In C# 5

    int? age = p == null ? null : p.Age;

    In C# 6

    int? age = p?.Age;

    The new syntax also has an advantage for firing events:

    In C# 5

    var handler = Event;

    if (handler != null)

    {

      handler(source, e);

    }

    In C# 6

    handler?.Invoke(source, e);

    The null propagation operator is covered in Chapter 8.

    String Interpolation

    The string interpolation removes calls to string.Format. Instead of using numbered format placeholders in the string, the placeholders can include expressions:

    In C# 5

    public override ToString()

    {

      return string.Format({0}, {1}, Title, Publisher);

    }

    In C# 6

    public override ToString() =>

    ${Title} {Publisher};

    The C# 6 sample is reduced that much compared to the C# 5 syntax because it uses not only string interpolation but also an expression-bodied method.

    String interpolation can also use string formats and get special features on assigning it to a FormattableString. String interpolation is covered in Chapter 10, Strings and Regular Expressions.

    Dictionary Initializers

    Dictionaries can now be initialized with a dictionary initializer—similar to the collection initializer.

    In C# 5

    var dict = new Dictionary();

    dict.Add(3,three);

    dict.Add(7,seven);

    In C# 6

    var dict = new Dictionary()

    {

      [3] =three,

      [7] =seven

    };

    Dictionary initializers are covered in Chapter 11, Collections.

    Exception Filters

    Exception filters allow you to filter exceptions before catching them.

    In C# 5

    try

    {

      //etc.

    }

    catch (MyException ex)

    {

      if (ex.ErrorCode != 405) throw;

      // etc.

    }

    In C# 6

    try

    {

      //etc.

    }

    catch (MyException ex) when (ex.ErrorCode == 405)

    {

      // etc.

    }

    A big advantage of the new syntax is not only that it reduces the code length but also that the stack trace is not changed—which happens with the C# 5 variant. Exception filters are covered in Chapter 14, Errors and Exceptions.

    Await in Catch

    await can now be used in the catch clause. C# 5 required a workaround.

    In C# 5

    bool hasError = false;

    string errorMessage = null;

    try

    {

      //etc.

    }

    catch (MyException ex)

    {

      hasError = true;

      errorMessage = ex.Message;

    }

    if (hasError)

    {

      await new MessageDialog().ShowAsync(errorMessage);

    }

    In C# 6

    try

    {

      //etc.

    }

    catch (MyException ex)

    {

      await new MessageDialog().ShowAsync(ex.Message);

    }

    This feature doesn’t need an enhancement of the C# syntax; it’s functionality that’s working now. This enhancement required a lot of investment from Microsoft to make it work, but that really doesn’t matter to you using this platform. For you, it means less code is needed—just compare the two versions.

    NOTE The new C# 6 language features are covered in the mentioned chapters, and in all chapters of this book the new C# syntax is used.

    What’s New with the Universal Windows Platform

    Windows 8 introduced a new programming API, the Windows Runtime. Applications using the Windows Runtime could be made available via the Microsoft Store and were known with many different names. It started with Metro apps or Metro style apps, and they are also known as Modern apps, Windows Store apps (although they can also be installed with PowerShell scripts without using the store), and Universal apps. Probably there are some names I missed. Nowadays, these are just Windows apps, running on the Universal Windows Platform (UWP).

    The idea of these apps was to allow end users to find them easily via the Microsoft store and to offer a touch-friendly environment, a modern user interface that looks nice and smooth and allows fluid interactions, and apps that can be trusted. More than that, the users who already know the Windows user interfaces should be attracted to using the new environment.

    The first version of the design guidelines was very restrictive and had some flaws. How can I search for stuff in the app? Many users didn’t find the charms bar on the right side, and found out it allowed searching in many apps. Windows 8.1 moved the search to a search box directly on the desktop. Also, users often didn’t find the app bar located at the top or bottom if they didn’t perform a touch gesture from top to bottom or bottom to top.

    Windows 10 made the design much more open. You can use the things that are useful for your apps and can decide on the user interface as it best matches your users and apps. Of course, it’s still best to create a nice looking, smooth, and fluid design. It’s better for having users happily interacting with the app, and they should not have a hard time finding out how things can be done.

    The new Windows Runtime, Windows Runtime 3.0, steps on the predecessor versions to define an XAML user interface, implements an application lifecycle, and allows background functionality, sharing of data between applications, and more. Indeed, the new version of the runtime offers more features in all the areas.

    Windows apps now make use of .NET Core. You can use the same .NET libraries available via NuGet packages with Windows apps. Finally, native code gets compiled for a faster app startup and less memory consumption.

    What might be even more important than the additional features offered is the universality that’s now available. The first update of Visual Studio 2013 included a new project type for Windows 8 apps: Universal apps. Here, Universal apps have been done with three projects: one project for the Windows app, one project for the Windows phone app, and a shared code project. It was possible to even share XAML code between these platforms. The new Universal project template consists of one project. You can use the same binary not only for Windows and Windows Phone, but also for the Xbox, Internet of Things (IoT) devices, the HoloLens, and more. Of course, these different platforms offer features that are not available everywhere, but using this differing feature you can still create one binary image that runs on every Windows 10 device.

    What You Need to Write and Run C# Code

    .NET Core runs on Windows, Linux, and Mac operating systems. You can create and build your programs on any of these operating systems using Visual Studio Code (https://code.visualstudio.com). The best developer tool to use, and the tool used with this book, is Visual Studio 2015. You can use Visual Studio Community 2015 edition (https://www.visualstudio.com), but some features shown are available only with the Enterprise edition of Visual Studio. It will be mentioned where the Enterprise edition is needed. Visual Studio 2015 requires the Windows operating system. Windows 8.1 or later is required.

    To build and run WPF applications shown in this book, you need a Windows platform. Running WPF applications is still supported on Windows 7.

    For building Universal Windows apps, you can use Windows 8.1 with Visual Studio, but for testing and running these apps, you need a Windows 10 device.

    What This Book Covers

    This book starts by reviewing the overall architecture of .NET in Chapter 1 to give you the background you need to write managed code. You’ll get an overview about the different application types and learn how to compile with the new development environment CLI. After that, the book is divided into a number of sections that cover both the C# language and its application in a variety of areas.

    Part I: The C# Language

    This section gives a good grounding in the C# language. This section doesn’t presume knowledge of any particular language, although it does assume you are an experienced programmer. You start by looking at C#’s basic syntax and data types and then explore the object-oriented features of C# before looking at more advanced C# programming topics like delegates, lambda expressions, Language Integrated Query (LINQ), reflection, and asynchronous programming.

    Part II: .NET Core and Windows Runtime

    This section starts with tools, and it looks at the main integrated development environment (IDE) utilized by C# developers worldwide: Visual Studio 2015. You’ll learn about the tools available with the Enterprise edition of Visual Studio in Chapter 17, Visual Studio 2015.

    You also learn what’s behind the C# compiler and how you can use the .NET Compiler Platform to change your code programmatically in Chapter 18, .NET Compiler Platform.

    When you’re creating functionality with C# code, don’t skip the step of creating unit tests. It takes more time in the beginning, but over time you’ll see advantages when you add functionality and maintain code. Chapter 19, Testing, covers creating unit tests, web tests, and coded UI tests.

    Chapters 20 to 28 cover topics from .NET Core and the Windows Runtime that are independent of application types. In Chapter 20, Diagnostics and Application Insights, you’ll learn writing diagnostic information from the application that can also be used in the production environment. Chapters 21, Tasks and Parallel Programming, and 22, Task Synchronization, cover parallel programming using the Task Parallel Library (TPL) as well as various objects for synchronization. In Chapter 23, Files and Streams, you’ll read about accessing the file system and reading files and directories. Using streams, you’ll learn using both streams from the System.IO namespace and streams from the Windows Runtime for programming Windows apps. Chapter 24, Security, makes use of streams when you learn about security and how to encrypt data and allow for secure conversion. You’ll also learn the core foundation of networking using sockets, as well as using higher-level abstractions like the HttpClient (Chapter 25, Networking). Chapter 26, Composition, covers Microsoft Composition that allows creating independence between containers and parts. In Chapter 27, XML and JSON, you learn about serializing objects into XML and JSON, as well as different techniques for reading and writing XML. Finally, in Chapter 28, Localization, you learn to localize applications using techniques for localizations that are important both for Windows and web applications.

    Part III: Windows Apps

    This section is about building applications with XAML—both Universal Windows apps and WPF. You’ll learn about the foundation of XAML in Chapter 29, Core XAML, with the XAML syntax, dependency properties, and also markup extensions where you can create your own XAML syntax. In Chapter 30, XAML Styles and Resources, you learn about styling your XAML-based apps. A big focus on the MVVM (model-view-view model) pattern is in Chapter 31, Patterns with XAML Apps. Here you learn to take advantage of the data-binding features of XAML-based applications, which allow sharing a lot of code between UWP apps and WPF applications. You can also share a lot of code for developing for the iPhone and Android platforms using Xamarin. However, developing with Xamarin is not covered in this book. After the introductory chapters covering both UWP apps and WPF applications, two chapters cover the specific features of UWP apps, and two chapters cover WPF applications. In Chapters 32, Windows Apps: User Interfaces, and 33, Advanced Windows Apps, you learn about specific XAML controls with UWP apps such as the RelativePanel and AdaptiveTrigger, the new compiled binding, and the application life cycle, sharing data, and creating background tasks. Chapters 34, Windows Desktop Applications with WPF, and 35, Creating Documents with WPF, go into WPF-specific features such as the Ribbon control, TreeView to show hierarchical data, WPF-specific data binding features, creating flow and fixed documents, and creating XML Paper Specification (XPS) files.

    This section is concluded with deployment in Chapter 36 to deploy WPF applications using ClickOnce, and information to get UWP apps in the store.

    Part IV: Web Applications and Services

    In this section you look at web applications and services. You’ll find two chapters about ADO.NET in this section as well. Although you can use ADO.NET (Chapter 37, ADO.NET) and the Entity Framework (Chapter 38, Entity Framework Core) from client applications as well, typically these technologies are used on the server, and you invoke services from the client.

    In Chapter 39, Windows Services, you can read how to create your own Windows services that run when the operating system is started.

    The new version of ASP.NET, ASP.NET Core 1.0, is covered in Chapter 40. Here you can read the foundation of ASP.NET and get ideas on how ASP.NET MVC 6 is built using these foundations. The features of ASP.NET MVC 6 are covered in Chapter 41.

    NOTE ASP.NET Web Forms are not covered in this book, although ASP.NET 4.6 offers new features for ASP.NET Web Forms. This book fully concentrates on the new version of ASP.NET technologies using ASP.NET Core 1.0. For information about ASP.NET Web Forms and ASP.NET MVC 5 you should read Professional C# 5 and .NET 4.5.1.

    Chapter 42 covers the REST service features of ASP.NET MVC 6: ASP.NET Web API. Publish and subscribe technologies for web applications, in the form of using the ASP.NET technologies WebHooks and SignalR, are covered in Chapter 43. Chapter 44 discusses an older technology for communication with services using SOAP and WCF.

    Again, like the previous section, this section concludes with deployment—deployment of websites running on Internet Information Server (IIS) or using Microsoft Azure to host websites.

    Conventions

    To help you get the most from the text and keep track of what’s happening, a number of conventions are used throughout the book.

    WARNINGS Warnings hold important, not-to-be-forgotten information that is directly relevant to the surrounding text.

    NOTE Notes indicate notes, tips, hints, tricks, and/or asides to the current discussion.

    As for styles in the text:

    We highlight new terms and important words when we introduce them.

    We show keyboard strokes like this: Ctrl+A.

    We show filenames, URLs, and code within the text like so: persistence.properties.

    We present code in two different ways:

    We use a monofont type with no highlighting for most code examples.

    We use bold to emphasize code that's particularly important in the present context or to show changes from a previous code snippet.

    Source Code

    As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All the source code used in this book is available for download at www.wrox.com/go/professionalcsharp6. When at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.

    NOTE Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-1-119-09660-3.

    After you download the code, just decompress it with your favorite compression tool. Alternatively, you can go to the main Wrox code download page at http://www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

    With the fast pace of updates with .NET Core, the source code of the book is also available at http://www .github.com/ProfessionalCSharp. Be aware that the source code on GitHub offers living source files that will be updated with minor update versions of Visual Studio, as well as new experimental C# features. For updates to the source code and additional samples done after the release of the book, check the GitHub site. The stable version of the source code that corresponds to the content of the printed book is available from the Wrox site.

    Errata

    We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be grateful for your feedback. By sending in errata you may save another reader hours of frustration, and at the same time you can help provide even higher-quality information.

    To find the errata page for this book, go to http://www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that have been submitted for this book and posted by Wrox editors. A complete book list including links to each book’s errata is also available at www.wrox.com/misc-pages/booklist.shtml.

    If you don’t spot your error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.

    p2p.wrox.com

    For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

    At http://p2p.wrox.com you can find a number of different forums to help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

    Go to p2p.wrox.com and click the Register link.

    Read the terms of use and click Agree.

    Complete the required information to join and any optional information you want to provide, and click Submit.

    You will receive an e-mail with information describing how to verify your account and complete the joining process.

    NOTE You can read messages in the forums without joining P2P but to post your own messages, you must join.

    After you join, you can post new messages and respond to messages other users post. You can read messages at any time on the web. If you want to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

    For more information about how to use the Wrox P2P, read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

    PART I

    The C# Language

    Chapter 1: .NET Application Architectures

    Chapter 2: Core C#

    Chapter 3: Objects and Types

    Chapter 4: Inheritance

    Chapter 5: Managed and Unmanaged Resources

    Chapter 6: Generics

    Chapter 7: Arrays and Tuples

    Chapter 8: Operators and Casts

    Chapter 9: Delegates, Lambdas, and Events

    Chapter 10: Strings and Regular Expressions

    Chapter 11: Collections

    Chapter 12: Special Collections

    Chapter 13: Language Integrated Query

    Chapter 14: Errors and Exceptions

    Chapter 15: Asynchronous Programming

    Chapter 16: Reflection, Metadata, and Dynamic Programming

    1

    .NET Application Architectures

    What’s In This Chapter?

    Reviewing the history of .NET

    Understanding differences between .NET Framework 4.6 and .NET Core 1.0

    Assemblies and NuGet Packages

    The Common Language Runtime

    Features of the Windows Runtime

    Programming Hello, World!

    Universal Windows Platform

    Technologies for creating Windows Apps

    Technologies for creating Web Apps

    Wrox.com Code Downloads for This Chapter

    The wrox.com code downloads for this chapter are found at www.wrox.com/go/professionalcsharp6 on the Download Code tab. The code for this chapter is divided into the following major examples:

    DotnetHelloWorld

    HelloWorldApp (.NET Core)

    Choosing Your Technologies

    In recent years, .NET has become a huge ecosystem for creating any kind of applications on the Windows platform. With .NET you can create Windows apps, web services, web applications, and apps for the Microsoft Phone.

    The newest release of .NET is a big change from the last version—maybe the biggest change to .NET since its invention. Much of the .NET code has become open-source code, and you can create applications for other platforms as well. The new version of .NET (.NET Core) and NuGet packages allow Microsoft to provide faster update cycles for delivering new features. It’s not easy to decide what technology should be used for creating applications. This chapter helps you with that. It gives you information about the different technologies available for creating Windows and web applications and services, offers guidance on what to choose for database access, and highlights the differences between .NET and .NET Core.

    Reviewing .NET History

    To better understand what is available with .NET and C#, it is best to know something about its history. The following table shows the version of .NET in relation to the Common Language Runtime (CLR), the version of C#, and the Visual Studio edition that gives some idea about the year when the corresponding versions have been released. Besides knowing what technology to use, it’s also good to know what technology is not recommended because there’s a replacement.

    The following sections cover the details of this table and the progress of C# and .NET.

    C# 1.0—A New Language

    C# 1.0 was a completely new programming language designed for the .NET Framework. At the time it was developed, the .NET Framework consisted of about 3,000 classes and the CLR.

    After Microsoft was not allowed by a court order (filed by Sun, the company that created Java) to make changes to the Java code, Anders Hejlsberg designed C#. Before working for Microsoft, Hejlsberg had his roots at Borland where he designed the Delphi programming language (an Object Pascal dialect). At Microsoft he was responsible for J++ (Microsoft’s version of the Java programming language). Given Hejlsberg’s background, the C# programming language was mainly influenced by C++, Java, and Pascal.

    Because C# was created later than Java and C++, Microsoft analyzed typical programming errors that happened with the other languages, and did some things differently to avoid these errors. Some differences include the following:

    With if statements, Boolean expressions are required (C++ allows an integer value here as well).

    It’s permissible to create value and reference types using the struct and class keywords (Java only allows creating custom reference types; with C++ the distinction between struct and class is only the default for the access modifier).

    Virtual and non-virtual methods are allowed (this is similar to C++; Java always creates virtual methods).

    Of course there are a lot more changes as you’ll see reading this book.

    At this time, C# was a pure object-oriented programming language with features for inheritance, encapsulation, and polymorphism. C# also offered component-based programming enhancements such as delegates and events.

    Before the existence of .NET with the CLR, every programming language had its own runtime. With C++, the C++ Runtime is linked with every C++ program. Visual Basic 6 had its own runtime with VBRun. The runtime of Java is the Java Virtual Machine—which can be compared to the CLR. The CLR is a runtime that is used by every .NET programming language. At the time the CLR appeared on the scene, Microsoft offered JScript.NET, Visual Basic .NET, and Managed C++ in addition to C#. JScript.NET was Microsoft’s JavaScript compiler that was to be used with the CLR and .NET classes. Visual Basic.NET was the name for Visual Basic that offered .NET support. Nowadays it’s just called Visual Basic again. Managed C++ was the name for a language that mixed native C++ code with Managed .NET Code. The newer C++ language used today with .NET is C++/CLR.

    A compiler for a .NET programming language generates Intermediate Language (IL) code. The IL code looks like object-oriented machine code and can be checked by using the tool ildasm.exe to open DLL or EXE files that contain .NET code. The CLR contains a just-in-time (JIT) compiler that generates native code out of the IL code when the program starts to run.

    NOTE IL code is also known as managed code.

    Other parts of the CLR are a garbage collector (GC), which is responsible for cleaning up managed memory that is no longer referenced; a security mechanism that uses code access security to verify what code is allowed to do; an extension for the debugger to allow a debug session between different programming languages (for example, starting a debug session with Visual Basic and continuing to debug within a C# library); and a threading facility that is responsible for creating threads on the underlying platform.

    The .NET Framework was already huge with version 1. The classes are organized within namespaces to help facilitate navigating the 3,000 available classes. Namespaces are used to group classes and to solve conflicts by allowing the same class name in different namespaces. Version 1 of the .NET Framework allowed creating Windows desktop applications using Windows Forms (namespace System.Windows.Forms), creating web applications with ASP.NET Web Forms (System.Web), communicating with applications and web services using ASP.NET Web Services, communicating more quickly between .NET applications using .NET Remoting, and creating COM+ components for running in an application server using Enterprise Services.

    ASP.NET Web Forms was the technology for creating web applications with the goal for the developer to not need to know something about HTML and JavaScript. Server-side controls that worked similarly to Windows Forms itself created HTML and JavaScript.

    C# 1.2 and .NET 1.1 was mainly a bug fix release with minor enhancements.

    NOTE Inheritance is discussed in Chapter 4, Inheritance; delegates and events are covered in Chapter 9, Delegates, Lambdas, and Events.

    NOTE Every new release of .NET has been accompanied by a new version of the book Professional C#. With .NET 1.0, the book was already in the second edition as the first edition had been published with Beta 2 of .NET 1.0. You’re holding the 10th edition of this book in your hands.

    C# 2 and .NET 2 with Generics

    C# 2 and .NET 2 was a huge update. With this version, a change to both the C# programming language and the IL code had been made; that’s why a new CLR was needed to support the IL code additions. One big change was generics. Generics make it possible to create types without needing to know what inner types are used. The inner types used are defined at instantiation time, when an instance is created.

    This advance in the C# programming language also resulted in many new types in the Framework—for example, new generic collection classes found in the namespace System.Collections.Generic. With this, the older collection classes defined with 1.0 are rarely used with newer applications. Of course, the older classes still work nowadays, even with the new .NET Core version.

    NOTE Generics are used all through the book, but they’re explained in detail in Chapter 6, Generics. Chapter 11, Collections, covers generic collection classes.

    .NET 3—Windows Presentation Foundation

    With the release of .NET 3.0 no new version of C# was needed. 3.0 was only a release offering new libraries, but it was a huge release with many new types and namespaces. Windows Presentation Foundation (WPF) was probably the biggest part of the new Framework for creating Windows desktop applications. Windows Forms wrapped the native Windows controls and was based on pixels, whereas WPF was based on DirectX to draw every control on its own. The vector graphics in WPF allow seamless resizing of every form. The templates in WPF also allow for complete custom looks. For example, an application for the Zurich airport can include a button that looks like a plane. As a result, applications can look very different from the traditional Windows applications that had been developed up to that time. Everything below the namespace System.Windows belongs to WPF, with the exception of System.Windows.Forms. With WPF the user interface can be designed using an XML syntax: XML for Applications Markup Language (XAML).

    Before .NET 3, ASP.NET Web Services and .NET Remoting were used for communicating between applications. Message Queuing was another option for communicating. The various technologies had different advantages and disadvantages, and all had different APIs for programming. A typical enterprise application had to use more than one communication API, and thus it was necessary to learn several of them. This was solved with Windows Communication Foundation (WCF). WCF combined all the options of the other APIs into the one API. However, to support all of the features WCF has to offer, you need to configure WCF.

    The third big part of the .NET 3.0 release was Windows Workflow Foundation (WF) with the namespace System.Workflow. Instead of creating custom workflow engines for several different applications (and Microsoft itself created several workflow engines for different products), a workflow engine was available as part of .NET.

    With .NET 3.0, the class count of the Framework increased from 8,000 types in .NET 2.0 to about 12,000 types.

    NOTE In this book, WPF is covered in Chapters 29, 30, 31, 34, 35, and 36. You can read information about WCF in Chapter 44, Windows Communication Foundation.

    C# 3 and .NET 3.5—LINQ

    .NET 3.5 came together with a new release of C# 3. The major enhancement was a query syntax defined with C# that allows using the same syntax to filter and sort object lists, XML files, and the database. The language enhancements didn’t require any change to the IL code as the C# features used here are just syntax sugar. All of the enhancements could have been done with the older syntax as well, just a lot more code would be necessary. The C# language makes it really easy to do these queries. With LINQ and lambda expressions, it’s possible to use the same query syntax and access object collections, databases, and XML files.

    For accessing the database and creating LINQ queries, LINQ to SQL was released as part of .NET 3.5. With the first update to .NET 3.5, the first version of Entity Framework was released. Both LINQ to SQL and Entity Framework offered mapping of hierarchies to the relations of a database and a LINQ provider. Entity Framework was more powerful, but LINQ to SQL was simpler. Over time, features of LINQ to SQL have been implemented in Entity Framework, and now this one is here to stay. (Nowadays it looks very different from the first version released.)

    Another technology introduced as part of .NET 3.5 was the System.AddIn namespace, which offers an add-in model. This model offers powerful features that run add-ins even out of process, but it is also complex to use.

    NOTE LINQ is covered in detail in Chapter 13, Language Integrated Query. The newest version of the Entity Framework is very different from the .NET 3.5 release; it’s described in Chapter 38, Entity Framework Core.

    C# 4 and .NET 4—Dynamic and TPL

    The theme of C# 4 was dynamic—integrating scripting languages and making it easier to use COM integration. C# syntax has been extended with the dynamic keyword, named and optional parameters, and enhancements to co- and contra-variance with generics.

    Other enhancements have been made within the .NET Framework. With multi-core CPUs, parallel programming had become more and more important. The Task Parallel Library (TPL), with abstractions of threads using Task and Parallel classes, make it easier to create parallel running code.

    Because the workflow engine created with .NET 3.0 didn’t fulfill its promises, a completely new Windows Workflow Foundation was part of .NET 4.0. To avoid conflicts with the older workflow engine, the newer one is defined in the System.Activity namespace.

    The enhancements of C# 4 also required a new version of the runtime. The runtime skipped from version 2 to 4.

    With the release of Visual Studio 2010, a new technology shipped for creating web applications: ASP.NET MVC 2.0. Unlike ASP.NET Web Forms, this technology required programming HTML and JavaScript, and it used C# and .NET with server-side functionality. As this technology was very new as well as being out of band (OOB) to Visual Studio and .NET, ASP.NET MVC was updated regularly.

    NOTE The dynamic keyword of C# 4 is covered in Chapter 16, Reflection, Metadata, and Dynamic Programming. The Task Parallel Library is covered in Chapter 21, Tasks and Parallel Programming.

    Version 5 of ASP.NET and Version 6 of ASP.NET MVC are covered in Chapter 40, ASP.NET Core, and Chapter 41, ASP.NET MVC.

    C# 5 and Asynchronous Programming

    C# 5 had only two new keywords: async and await. However, they made programming of asynchronous methods a lot easier. As touch became more significant with Windows 8, it also became a lot more important to not block the UI thread. Using the mouse, users are accustomed to scrolling taking some time. However, using fingers on a touch interface that is not responsive is really annoying.

    Windows 8 also introduced a new programming interface for Windows Store apps (also known as Modern apps, Metro apps, Universal Windows apps, and, more recently, Windows apps): the Windows Runtime. This is a native runtime that looks like .NET by using language projections. Many of the WPF controls have been redone for the new runtime, and a subset of the .NET Framework can be used with such apps.

    As the System.AddIn framework was much too complex and slow, a new composition framework was created with .NET 4.5: Managed Extensibility Framework with the namespace System.Composition.

    A new version of platform-independent communication is offered by the ASP.NET Web API. Unlike WCF, which offers stateful and stateless services as well as many different network protocols, the ASP.NET Web API is a lot simpler and based on the Representational State Transfer (REST) software architecture style.

    NOTE The async and await keywords of C# 5 are discussed in detail in Chapter 15, Asynchronous Programming. This chapter also shows the different asynchronous patterns that have been used over time with .NET.

    Managed Extensibility Framework (MEF) is covered in Chapter 26, Composition. Windows apps are covered in Chapters 29 to 33, and the ASP.NET Web API is covered in Chapter 42, ASP.NET Web API.

    C# 6 and .NET Core

    C# 6 doesn’t involve the huge improvements that were made by generics, LINQ, and async, but there are a lot of small and practical enhancements in the language that can reduce the code length in several places. The many improvements have been made possible by a new compiler engine code named Roslyn.

    NOTE Roslyn is covered in Chapter 18, .NET Compiler Platform.

    The full .NET Framework is not the only .NET Framework that was in use in recent years. Some scenarios required smaller frameworks. In 2007, the first version of Microsoft Silverlight was released (code named WPF/E, WPF Everywhere). Silverlight was a web browser plug-in that allowed dynamic content. The first version of Silverlight supported programming only via JavaScript. The second version included a subset of the .NET Framework. Of course, server-side libraries were not needed because Silverlight was always running on the client, but the Framework shipped with Silverlight also removed classes and methods from the core features to make it lightweight and portable to other platforms. The last version of Silverlight for the desktop (version 5) was released in December 2011. Silverlight had also been used for programming for the Windows Phone. Silverlight 8.1 made it into Windows Phone 8.1, but this version of Silverlight is also different from the version on the desktop.

    On the Windows desktop, where there is such a huge framework with .NET and the need for faster and faster development cadences, big changes were also required. In a world of DevOps where developers and operations work together or are even the same people to bring applications and new features continuously to the user, there’s a need to have new features available in a fast way. Creating new features or making bug fixes is a not-so-easy task with a huge framework and many dependencies.

    With several smaller .NET Frameworks available (e.g. Silverlight, Silverlight for the Windows Phone), it became important to share code between the desktop version of .NET and a smaller version. A technology to share code between different .NET versions is the portable library. Over time, with many different .NET Frameworks and versions, the management of the portable library has become a nightmare.

    With all these issues, a new version of .NET is a necessity. (Yes, it’s really a requirement to solve these issues.) The new version of the Framework is invented with the name .NET Core. .NET Core is smaller with modular NuGet packages, has a runtime that’s distributed with every application, is open source, and is available not only for the desktop version of Windows but also for many different Windows devices, as well as for Linux and OS X.

    For creating web applications, ASP.NET Core 1.0 is a complete rewrite of ASP.NET. This release is not completely backward compatible to older versions and requires some changes to existing ASP.NET MVC code (with ASP.NET MVC 6). However, it also has a lot of advantages when compared with the older versions, such as a lower overhead with every network request—which results in better performance—and it can also run on Linux. ASP.NET Web Forms is not part of this release because ASP.NET Web Forms was not designed for best performance; it was designed for developer friendliness based on patterns known by Windows Forms application developers.

    Of course, not all applications can be changed easily to make use of .NET Core. That’s why the huge framework received improvements as well—even if those improvements are not completed in as fast a pace as .NET Core. The new version of the full .NET Framework is 4.6. Small updates for ASP.NET Web Forms are available on the full .NET stack.

    NOTE Roslyn is covered in Chapter 18. The changes to the C# language are covered in all the language chapters in Part I—for example, read-only properties are in Chapter 33, Objects and Types; the nameof operator and null propagation are in Chapter 8, Operators and Casts; string interpolation is in Chapter 10, Strings and Regular Expressions; and exception filters are in Chapter 14, Errors and Exceptions.

    Where possible, .NET Core is used in this book. You can read more information about .NET Core and NuGet packages later in this chapter.

    Choosing Technologies and Going Forward

    When you know the reason for competing technologies within the Framework, it’s easier to select a technology to use for programming applications. For example, if you’re creating new Windows applications it’s not a good idea to bet on Windows Forms. Instead, you should use an XAML-based technology, such as Windows apps or Windows desktop applications using WPF.

    If you’re creating web applications, a safe bet is to use ASP.NET Core with ASP.NET MVC 6. Making this choice rules out using ASP.NET Web Forms. If you’re accessing a database, you should use Entity Framework rather than LINQ to SQL, and you should opt for the Managed Extensibility Framework instead of System.AddIn.

    Legacy applications still use Windows Forms and ASP.NET Web Forms and some other older technologies. It doesn’t make sense to change existing applications just to use new technologies. There must be a huge advantage to making the change—for example, when maintenance of the code is already a nightmare and a lot of refactoring is needed to change to faster release cycles that are being demanded by customers, or when using a new technology allows for reducing the coding time for updates. Depending on the type of legacy application, it might not be worthwhile to switch to a new technology. You can allow the application to still be based on older technologies because Windows Forms and ASP.NET Web Forms will still be supported for many years to come.

    The content of this book is based on the newer technologies to show what’s best for creating new applications. In case you still need to maintain legacy applications, you can refer to older editions of this book, which cover ASP.NET Web Forms, Windows Forms, System.AddIn, and other legacy technologies that are still part of and available with the .NET Framework.

    .NET 2015

    .NET 2015 is an umbrella term for all the .NET technologies. Figure 1.1 gives an overall picture of these technologies. The left side represents the .NET Framework 4.6 technologies such as WPF and ASP.NET 4. ASP.NET Core 1.0 can run on .NET Framework 4.6 as well, as you can see in this figure. The right side represents the new .NET Core technologies. Both ASP.NET Core 1.0 and the Universal Windows Platform (UWP) run on .NET Core. You can also create console applications that run on .NET Core.

    Block diagram shows .NET Framework 4.6 technologies such as WPF, ASP.NET 4.x, Core 1.0 and .Net Core 1.0 technologies such as ASP.NET Core 1.0 and Universal Windows Apps along with shared Runtime components, libraries, and compiler.

    Figure 1.1

    A part of .NET Core is a new runtime: the CoreCLR. This runtime is used from ASP.NET Core 1.0. Instead of using the CoreCLR runtime, .NET can also be compiled to native code. The UWP automatically makes use of this feature; these .NET applications are compiled to native code before being offered from the Windows Store. You can also compile other .NET Core applications—and the applications running on Linux—to native code.

    In the lower part of Figure 1.1, you can see there’s also some sharing going on between .NET Framework 4.6 and .NET Core. Runtime components, such as the code for the garbage collector and the RyuJIT (this is a new JIT compiler to compile IL code to native code) are shared. The garbage collector is used by CLR, CoreCLR, and .NET Native. The RyuJIT just-in-time compiler is used by CLR and CoreCLR. Libraries can be shared between applications based on the .NET Framework 4.6 and .NET Core 1.0. The concept of NuGet packages helps put these libraries in a common package that is available on all .NET platforms. And, of course, the new .NET compiler platform is used by all these technologies.

    .NET Framework 4.6

    NET Framework 4.6 is the .NET Framework that has been continuously enhanced in the past 10 years. Many of the technologies that have been discussed in the history section are based on this framework. This framework is used for creating Windows Forms and WPF applications. Also, although ASP.NET 5 can run on .NET Core, it can also run on .NET Framework 4.6.

    If you want to continue working with ASP.NET Web Forms, ASP.NET 4.6 with .NET Framework 4.6 is the way to go. ASP.NET 4.6 also has new features compared to version 4.5, such as support for HTTP2 (a new version of the HTTP protocol that is discussed in Chapter 25, Networking), compilation on the fly with the Roslyn compiler, and asynchronous model binding. However, you can’t switch to .NET Core with ASP.NET Web Forms.

    You can find the libraries of the framework as well as the CLR in the directory %windows%\Microsoft .NET\Framework\v4.0.30319.

    The classes available with the .NET Framework are organized in namespaces starting with the name System. The following table describes a few of the namespaces to give you an idea about the hierarchy.

    NOTE Some of the new .NET classes use namespaces that start with the name Microsoft instead of System, like Microsoft.Data.Entity for the Entity Framework and Microsoft.Extensions.DependencyInjection for the new dependency injection framework.

    .NET Core 1.0

    .NET Core 1.0 is the new .NET that is used by all new technologies and has a big focus in this book. This framework is open source—you can find it at http://www.github.com/dotnet. The runtime is the CoreCLR repository; the framework containing collection classes, file system access, console, XML, and a lot more is in the CoreFX repository.

    Unlike the .NET Framework, where the specific version you needed for the application had to be installed on the system, with .NET Core 1.0 the framework, including the runtime, is delivered with the application. Previously there were times when you might have had problems deploying an ASP.NET web application to a shared server because the provider had older versions of .NET installed; those times are gone. Now you can deliver the runtime with the application and are not dependent on the version installed on the server.

    .NET Core 1.0 is designed in a modular approach. The framework splits up into a large list of NuGet packages. With the application you decide what packages you need. The .NET Framework was growing larger and larger when new functionality was added. It was not possible to remove old functionality that’s no longer needed, such as the old collection classes that are unnecessary because of the generic collection classes that were added, .NET Remoting that has been replaced by the new communication technology, or LINQ to SQL that has been updated to Entity Framework. Applications can break when something is removed. This does not apply to .NET Core, as the application distributes the parts of the framework that it needs.

    The framework of .NET Core is currently as huge as .NET Framework 4.6 is. However, this can change, and it can grow even bigger, but because of the modularity that growth potential is not an issue. .NET Core is already so huge that we can’t cover every type in this book. Just have a look at http://www.github.com/dotnet/corefx to see all the sources. For example, old nongeneric collection classes are already covered with .NET Core to make it easier to bring legacy code to the new platform.

    .NET Core can be updated at a fast pace. Even updating the runtime doesn’t influence existing applications because the runtime is installed with the applications. Now Microsoft can improve .NET Core, including the runtime, with faster release cycles.

    NOTE For developing apps using .NET Core, Microsoft created new command-line utilities named .NET Core Command line (CLI). These tools are introduced later in this chapter through a Hello, World! application in the section Compiling with CLI.

    Assemblies

    Libraries and executables of .NET programs are known by the term assembly. An assembly is the logical unit that contains compiled IL code targeted at the .NET Framework.

    An assembly is completely self-describing and is a logical rather than a physical unit, which means that it can be stored across more than one file. (Indeed, dynamic assemblies are stored in memory, not on file.) If an assembly is stored in more than one file, there will be one main file that contains the entry point and describes the other files in the assembly.

    The same assembly structure is used for both executable code and library code. The only difference is that an executable assembly contains a main program entry point, whereas a library assembly does not.

    An important characteristic of assemblies is that they contain metadata that describes the types and methods defined in the corresponding code. An assembly, however, also contains assembly metadata that describes the assembly. This assembly metadata, contained in an area known as the manifest, enables checks to be made on the version of the assembly and on its integrity.

    Because an assembly contains program metadata, applications or other assemblies that call up code in a given assembly do not need to refer to the registry, or to any other data source, to find out how to use that assembly.

    With the .NET Framework 4.6, assemblies come in two types: private and shared assemblies. Shared assemblies don’t apply to the Universal Windows Platform because all the code is compiled to one native image.

    Private Assemblies

    Private assemblies normally ship with software and are intended to be used

    Enjoying the preview?
    Page 1 of 1