buunguyen / fasterflect

.NET Reflection Made Fast and Simple ⛺
https://www.nuget.org/packages/fasterflect/
Apache License 2.0
283 stars 55 forks source link

Call generic method with out parameter throws NullReferenceException without Flags.ExactBinding #16

Open markjerz opened 3 years ago

markjerz commented 3 years ago

I added the following method to Host in GenericTest:

public bool TryGet<T1, T2>(T2 obj1, out T1 obj2)
{
    obj2 = default;
    return true;
}

If I DO NOT include the Flags as below then it throws a NullReferenceException in MemberFilter when it attempts to call SubString on the name variable inside if( ignoreParameterModifiers && parameterType.IsByRef ). This is because the parameterType.FullName is null as the parameterType is generic.

[TestMethod]
public void Test_invoke_instance_generic_out()
{
    var target = typeof(Host).CreateInstance();
    var parameters = new object[] {1, null};
    var result = (bool)target.CallMethod(new[] {typeof(string), typeof(int)}, "TryGet",
                new[] {typeof(int), typeof(string).MakeByRefType()}, Flags.ExactBinding | Flags.InstancePublicDeclaredOnly, parameters);
    Assert.IsTrue(result);
    Assert.AreEqual(null, parameters[1]);
}

To work around this current problem, as I've done here, you must specify Flags.ExactBinding which then skips that particular bit of code.

Apologies, for not providing a PR with a failing test - I just had time to figure out a workaround and to then write it here so that somebody might fix in the future (or find the workaround!)