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 following implementation...