Click here to Skip to main content
15,312,747 members
Articles / All Topics
Technical Blog
Posted 30 Jul 2010

Tagged as

Stats

25.5K views
4 bookmarked

out, ref and InvokeMember !!!

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
30 Jul 2010CPOL
How to pass out or ref parameters for the method invoked using Type.InvokeMember?

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

C#
int DoSomething(string someString, int someInt);

then you would use InvokeMember like this:

C#
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 do with the args if DoSomething takes out or ref parameters?

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

Something like this will not work:

C#
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.

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

or even surprisingly this works:

C#
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 !!!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Vivek Ragunathan
Architect
United States United States
No Biography provided

Comments and Discussions

 
AnswerWhy it works Pin
njshaw27-Nov-14 0:10
Membernjshaw27-Nov-14 0:10 
QuestionThanks Pin
BouncingSoul28-Jul-13 22:45
MemberBouncingSoul28-Jul-13 22:45 
QuestionTest This Pin
mcpoo7261-Feb-13 12:47
Membermcpoo7261-Feb-13 12:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.