Ken
Ken

Reputation: 102

How do I get the parameter types of a custom C# dynamic method if args are passed as null?

I have been working with creating a custom C# DynamicObject class. I have overloaded TryInvokeMember() and have it working except for some methods that use out parameters. I need to be able to get the types of the parameters being passed into the dynamic method as part of the translation logic that I have to implement. Unfortunately, it would appear as though out parameters come in as null in the TryInvokeMethod args array object. I cannot get the type of a null object. I need to be able to get the type of the argument so that I can use reflection to create a new object of the out parameter type being passed in. I am hoping I can assign the new object to the out parameter.

Is what I am describing even possible with custom dynamic methods? If so, how do I get the type of the dynamic method out parameters if they are null?

I have tried to use DynamicMethod.GetCurrentMethod().GetParameters(), but this returns the TryInvokeMember parameters.

I've also tried getting the InvokeMethodBinder.CallInfo object, but this only has the names and argument count of the parameters, and not the parameter types (at least as far as I can tell).

Upvotes: 1

Views: 58

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112352

"I cannot get the type of a null object": null is not an object; it is the absence of an object and it has no type.

I don't know whether this is an option in your current scenario, but you could create a Null<T> class:

public class Null<T>
{
    private Null() { }

    public static Null<T> Instance { get; } = new Null<T>();
}

Then you can replace a null parameter by (as an example for (string)null): Null<string>.Instance. This allows you to determine the type with reflection.

Note that it may be useful to use an expression like (string)null in some cases. But this does not create a typed null. It determines the static return type of the expression.

Upvotes: 1

Related Questions