out, ref and InvokeMember !!!

When I was working on the .NET reflection extravaganza thing that I explained in my previous column, i learnt one another interesting thing, that is about the Type.InvokeMember. How will pass out or ref parameters for the method invoked using Type.InvokeMember ? If you are going to invoke a method with the prototype

int DoSomething(string someString, int someInt);

then you would use InvokeMember like this:-

object obj = someType.InvokeMember("DoSomething",   
	BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,   
	null,   
	this,   
	new object[] {"Largest Integer", 1});

or use some variables in the new object[] {…}. But what do you with the args if DoSomething takes out or ref parameters ?

int DoSomething(out string someString, ref int someInt);

Something like this will not work

string someText = string.Empty;   
int someInt = 0;   
object obj = someType.InvokeMember("DoSomething",   
	BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,   
	null,   
	this,   
	new object[] {someText, someInt});

It is tricky.

object[] args = new object[] { someText, someInt };   
object obj = someType.InvokeMember("DoSomething",   
	BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,   
	null,   
	this,   
	args);

or even suprisingly this works:-

object[] args = new object[2];   
// or object[] args = new object[] { null, null };            

object obj = someType.InvokeMember("DoSomething",   
	BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,   
	null,   
	this,   
	args);

Access the values by indexing args. So declaring the argument object[] as a local variable solves the problem, but I do not understand why this behaviour. May be somebody can explain !!!

Advertisements

One Response to out, ref and InvokeMember !!!

  1. programming quote…

    […]out, ref and InvokeMember !!! « Name it Later[…]…

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: