Book Image

Learn C# Programming

By : Marius Bancila, Raffaele Rialdi, Ankit Sharma
5 (1)
Book Image

Learn C# Programming

5 (1)
By: Marius Bancila, Raffaele Rialdi, Ankit Sharma

Overview of this book

The C# programming language is often developers’ primary choice for creating a wide range of applications for desktop, cloud, and mobile. In nearly two decades of its existence, C# has evolved from a general-purpose, object-oriented language to a multi-paradigm language with impressive features. This book will take you through C# from the ground up in a step-by-step manner. You'll start with the building blocks of C#, which include basic data types, variables, strings, arrays, operators, control statements, and loops. Once comfortable with the basics, you'll then progress to learning object-oriented programming concepts such as classes and structures, objects, interfaces, and abstraction. Generics, functional programming, dynamic, and asynchronous programming are covered in detail. This book also takes you through regular expressions, reflection, memory management, pattern matching, exceptions, and many other advanced topics. As you advance, you'll explore the .NET Core 3 framework and learn how to use the dotnet command-line interface (CLI), consume NuGet packages, develop for Linux, and migrate apps built with .NET Framework. Finally, you'll understand how to run unit tests with the Microsoft unit testing frameworks available in Visual Studio. By the end of this book, you’ll be well-versed with the essentials of the C# language and be ready to start creating apps with it.
Table of Contents (20 chapters)

Type parameter constraints

The type parameters in a generic type or method can be replaced by any valid type. However, there are scenarios when we want to restrict the types that can be used for a type parameter. Take, for instance, the generic Shape<T> class or the IShape<T> interface we saw earlier.

The type parameter T was used for the type of the Area property. We would expect that to be either an integral type or a floating-point type. But there is no restriction and someone could use bool, string, or any other type. Of course, depending on the way the type parameter is used, that could lead to various compiler errors. However, it is useful to be able to restrict the types used to instantiate generic types or call generic methods.

For this purpose, we can apply constraints to the type parameters. The constraints are used to inform the compiler about what kind of capabilities the type parameter must have. If we do not specify a constraint, then the type parameter...