Contravariance in action lambda - C #

I have a class hierarchy like this

public abstract class CalendarEventBase{}

public class TrainingEvent : CalendarEventBase{}

public class AuditEvent : CalendarEventBase{}

I wanted to create an Actionda Action that had the typical paramater type of type CalendarEventBase, which I could assign to the following various methods:

public void EmailCancelation(TrainingEvent trainingEvent)

public void EmailCancelation(AuditEvent auditEvent)

I created the following illegal assignment:

Action<CalendarEventBase> emailCancelation = _trainingService.EmailTrainingCancellation;

The compiler complains that it was expecting a method with void (CalendarEventBase) to become a signature. I was surprised at this, as I thought it would take on a more derived type.

To get around this, I created the following delegate, which allows me to complete my task:

public delegate void EmailCancelation<in T>(T calendarEvent) where T : CalendarEventBase;

My question is: could I complete the task without having to create an additional delegate? I thought I could just create an Action instance.

Any help or pointers greatly appreciated.

+5
2

:

Action<CalendarEventBase> emailCancelation = _trainingService.EmailTrainingCancellation;

, . ; TrainingEvent - (CalendarEventBase)?

:

// What if the method wants to make the lion roar but you pass in a goat?
Action<Mammal> mammalAction = MethodThatTakesALion; 

:

// Anything that you want to with an animal, you can do with a mammal.
Action<Mammal> mammalAction = MethodThatTakesAnAnimal; 
+7

, emailCancelation CalendarEventBase, TrainingEvent. , - emailCancelation AuditEvent?

+1

All Articles