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; }
}
}