jeudi 16 mars 2017

Delegate return type different with lambda function

Consider this MCVE:

using System;

public interface IThing { }

public class Foo : IThing
{
    public static Foo Create() => new Foo();
}

public class Bar : IThing
{
    public static Bar Create() => new Bar();
}

public delegate IThing ThingCreator();

class Program
{
    static void Test(ThingCreator creator)
    {
        Console.WriteLine(creator.Method.ReturnType);
    }

    static void Main()
    {
        Test(Foo.Create);      // Prints: Foo
        Test(Bar.Create);      // Prints: Bar

        Test(() => new Foo()); // Prints: IThing
        Test(() => new Bar()); // Prints: IThing
    }
}

Why does reflecting the return type for the static factory method give the concrete type, while calling the constructor inline gives the interface? I would expect them to both be the same.

Also, is there a way to specify in the lambda version that I want the return value to be the concrete type? Or is calling a static method the only way to do that?





Aucun commentaire:

Enregistrer un commentaire