Question

I have some code that was written for C# 4.0+, that I really need to compile with a C# 2.0 compiler.

The following snippets I don't really how to write, in order to support the same functionality:

public sealed class MyClass
{
    private static readonly GenericStaticMethod _deserializeHelper = new GenericStaticMethod(() => DeserializeHelper<object>(null, null, null));
    //...
}

public sealed class GenericStaticMethod
{
    private readonly MethodInfo methodToCall;

    public GenericStaticMethod(Expression<Action> methodCall)
    {
        var callExpression = (MethodCallExpression)methodCall.Body;
        methodToCall = callExpression.Method.GetGenericMethodDefinition();
    }

    public object Invoke(Type[] genericArguments, params object[] arguments)
    {
        try
        {
            return methodToCall
                .MakeGenericMethod(genericArguments)
                .Invoke(null, arguments);
        }
        catch (TargetInvocationException ex)
        {
            throw ex.Unwrap();
        }
    }
}

The expression that cannot be written this way is:

() => DeserializeHelper<object>(null, null, null)

A straight substitution for a delegate doesn't work without modifications of GenericStaticMethod():

delegate() { return DeserializeHelper<object>(null, null, null); }

Rewriting GenericStaticMethod could be acceptable, but I don't know how to.

Was it helpful?

Solution

You just plain cannot use expression trees in your case, they only get compiler support in later versions. But you don't need to, if the only reason you use it is to get the MethodInfo in a strongly-typed fashion.

public sealed class MyClass
{
    private static readonly GenericStaticMethod _deserializeHelper = new GenericStaticMethod(new Action<object, object, object>(DeserializeHelper<object>));
}

public sealed class GenericStaticMethod
{
    private readonly MethodInfo methodToCall;

    public GenericStaticMethod(Delegate methodCall)
    {
        methodToCall = methodCall.Method.GetGenericMethodDefinition();
    }
}

You'll need to change Action<object, object, object> to a delegate type that matches the signature of DeserializeHelper<object>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top