Home Why can't the compiler figure out that this lambda is a Delegate?
Reply: 0

Why can't the compiler figure out that this lambda is a Delegate?

user1362
1#
user1362 Published in June 19, 2018, 2:23 pm

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

  1. the () => {} lambda is an Action,
  2. the Action is a Delegate, and
  3. therefor that the () => {} lambda is a Delegate.

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 { }
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.574571 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO