Generic delegate type parameter variance - CSharp Custom Type

CSharp examples for Custom Type:delegate

Introduction

If you're defining a generic delegate type, it's good practice to:

  • Mark a type parameter used only on the return value as covariant (out).
  • Mark any type parameters used only on parameters as contravariant (in).

Doing so allows conversions to work naturally by respecting inheritance relationships between types.

The following delegate defined in the System namespace has a covariant TResult:

delegate TResult Func<out TResult>();

allowing:

Func<string> x = ...;
Func<object> y = x;

The following delegate defined in the System namespace has a contravariant T:

delegate void Action<in T> (T arg);

allowing:

Action<object> x = ...;
Action<string> y = x;

Related Tutorials