SilentSin
SilentSin

Reputation: 1036

Using reflection methods that take array parameters efficiently

Currently I'm using some static arrays to avoid creating garbage for reflection methods that take arrays:

public static readonly object[]
    OneObject = new object[1],
    TwoObjects = new object[2];

Then I use them like:

public void Write(BinaryWriter writer, object value)
{
    Reflection.TwoObjects[0] = writer;
    Reflection.TwoObjects[1] = value;
    WriteMethod.Invoke(null, Reflection.TwoObjects);
}

Most of the time this will be fine, but it opens the door to multithreading bugs.

Is there a better way of doing this without allocating tiny arrays all over the place?

Upvotes: 2

Views: 147

Answers (1)

wablab
wablab

Reputation: 1743

If you know the signature of the underlying method, you can create a strongly typed delegate and invoke it instead. For example (assuming method is a MethodInfo instance that represents a static method that returns void and takes a BinaryWriter and an object as parameters):

var myMethod = (Action<BinaryWriter, object>)Delegate.CreateDelegate(typeof(Action<BinaryWriter, object>), method);
myMethod(writer, obj);

An added benefit of this is that invoking the delegate doesn't incur the same performance overhead that using MethodInfo.Invoke incurs.

Upvotes: 2

Related Questions