0

Why does creating a compiled Delegate for a GetMethod of a property throws the following argumentexception when the implementing type is a struct?

ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

I found a few posts here on SO which deal with a similiar problem, where the func-type is incorrect. However i cant see what I am doing wrong here.

Accessing the property through a Delegate created using a Lambdaexpression works fine however. Same goes for changing struct to class.

Complete program for demonstration (does not run in .net-Fiddle)

using System;
using System.Linq.Expressions;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        PropertyInfo propInfo = typeof (TestStruct).GetProperty("Property");


        TestStruct value = new TestStruct
        {
            Property = "Hello World!!1 from Reflection"
        };


        // This doesnt work
        try
        {
            Func<TestStruct,string> functionFromRelfection = (Func<TestStruct,string>) Delegate.CreateDelegate(typeof (Func<TestStruct,string>), propInfo.GetGetMethod());
            Console.WriteLine(functionFromRelfection(value));
        }
        catch (Exception e)
        {
             // Breakpoint goes here
        }

        value = new TestStruct
        {
            Property = "Hello World!!1 from Expression"
        };

        // This works
        ParameterExpression parameter = Expression.Parameter(typeof(TestStruct));
        MemberExpression member = Expression.Property(parameter, propInfo);

        LambdaExpression lambda = Expression.Lambda<Func<TestStruct, string>>(member, parameter);

        Func<TestStruct, string> functionFromExpression = (Func<TestStruct, string>)lambda.Compile();
        Console.WriteLine(functionFromExpression(value));

        Console.ReadKey();
    }

    public struct TestStruct
    {
        public string Property { get; set; }
    }
}
Community
  • 1
  • 1
CSharpie
  • 9,195
  • 4
  • 44
  • 71
  • you missed that `get_Property` func does not have any params and have next signature for your case `System.String get_Property()` – Grundy Apr 10 '15 at 17:58
  • I dont get what you mean, the problem is that if you change struct to class it works. How do you explain this? Also the "instance" parameter is nescessary since the Property isnt static. – CSharpie Apr 10 '15 at 18:05
  • seems like `CreateDelegate` can't work with MethodInfo from struct, i try with simple functin - same result – Grundy Apr 10 '15 at 18:41

0 Answers0