Luca
Luca

Reputation: 11961

Get method by reflection fails

I have the following method delared by Gl:

public static void Get(int pname, out int @params)

I'm trying to get it using reflection in the following way:

MethodInfo mGetMethod = typeof(Gl).GetMethod("Get",
                                             BindingFlags.Public|BindingFlags.Static,
                                             null, 
                                             new Type[] 
                                             { 
                                                 typeof(Int32), 
                                                 typeof(Int32) 
                                             }, 
                                             null);

But I have no success. Why?

Is it because the out keyword?

Upvotes: 2

Views: 1092

Answers (4)

Isaac Overacker
Isaac Overacker

Reputation: 1535

Use typeof(Int32).MakeByRefType() for your second parameter. I.e.:

MethodInfo mGetMethod = typeof(Gl).GetMethod("Get", bindingFlags.Public|BindingFlags.Static, null, new Type[] { typeof(Int32), typeof(Int32).MakeByRefType() }, null);

Upvotes: 7

kmkemp
kmkemp

Reputation: 1666

The out keyword passes the parameter by reference, which is probably your problem. You will need to flag it as a reference type since C# allows you to overload methods with a byValue and byReference parameter.

Upvotes: 1

Chris Haas
Chris Haas

Reputation: 55427

If you need to specify the specific overload for the method then definitely go with what @Isaac Overacker said. Otherwise just don't specify the parameters:

MethodInfo mGetMethod = typeof(Gl).GetMethod("Get", BindingFlags.Public | BindingFlags.Static);

Upvotes: 1

James Johnson
James Johnson

Reputation: 46047

How about trying something like this instead:

MethodInfo method = this.GetType().GetMethod("Get");
if (method != null)
{
    method.Invoke(this, new object[] { "Arg1", "Arg2", "Arg3" });
}

Upvotes: 0

Related Questions