Book Image

Functional C#

Book Image

Functional C#

Overview of this book

Functional programming makes your application faster, improves performance, and increases your productivity. C# code is written at a higher level of abstraction, so that code will be closer to business requirements, abstracting away many low-level implementation details. This book bridges the language gap for C# developers by showing you how to create and consume functional constructs in C#. We also bridge the domain gap by showing how functional constructs can be applied in business scenarios. We’ll take you through lambda expressions and extension methods, and help you develop a deep understanding of the concepts and practices of LINQ and recursion in C#. By the end of the book, you will be able to write code using the best approach and will be able to perform unit testing in functional programming, changing how you write your applications and revolutionizing your projects.
Table of Contents (19 chapters)
Functional C#
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Distinguishing variance in delegates


A generic delegate has the ability to be assigned by a method that has an unmatched signature to the delegate. We can call this variance in delegates. There are two variances in delegates, and they are covariance and contravariance. Covariance allows a method to have a return type that is more derived (subtype) than the return type that is defined in the delegate. On the other hand, contravariance allows a method to have parameter types that are less derived (supertype) than the parameter types that are defined in the delegate.

Covariance

The following is an example of covariance in delegates, which we can find in the Covariance.csproj project. First, we initialize the following delegate:

public partial class Program 
{ 
  private delegate TextWriter CovarianceDelegate(); 
} 

We now have a delegate returning the TextWriter data type. Then, we also create the StreamWriterMethod() method returning the StreamWriter object, which has the...