Consider this tiny program.
public class Program
{
public static void Main()
{
// the first path compiles
RunAction(() => { });
// the second path does not compile
RunDelegate(() => {});
}
private static void RunAction(Action run) => RunDelegate(run);
private static void RunDelegate(Delegate run) { }
}
The first path compiles and implies that
- the
() => {}
lambda is anAction
, - the
Action
is aDelegate
, and - therefor that the
() => {}
lambda is aDelegate
.
Why does the second path not compile?
Usually the compiler is able to make the leap between steps (1) and (3). Here is an example of how the compiler usually handles this kind of nested is-a relationships.
public class Program2
{
public static void Main()
{
// both of these comple
AcceptPerson(new Programmer());
AcceptAnimal(new Programmer());
}
private static void AcceptPerson(Person p) => AcceptAnimal(p);
private static void AcceptAnimal(Animal a) { }
}
public class Programmer : Person { }
public class Person : Animal { }
public class Animal { }