Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass parameters by ref when calling a static method using reflection?

I'm calling a static method on an object using reflection:

MyType.GetMethod("MyMethod", BindingFlags.Static).Invoke(null, new object[] { Parameter1, Parameter2 });

How do you pass parameters by ref, rather that by value? I assume they would be by value by default. The first parameter ("Parameter1" in the array) should be by ref, but I can't figure out how to pass it that way.

like image 812
Deane Avatar asked Apr 24 '09 16:04

Deane


People also ask

Can a static function have an argument with ref keyword?

13.5.It shall be illegal to use argument passing by reference for subroutines with a lifetime of static.

What are ref parameters?

A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method.

What is invoke method in C#?

Invoke(Object, Object[]) Invokes the method or constructor represented by the current instance, using the specified parameters. Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)

How does the ref modifier change a function or method parameter?

The ref Modifier By default, a reference type passed into a method will have any changes made to its values reflected outside the method as well. If you assign the reference type to a new reference type inside the method, those changes will only be local to the method.


1 Answers

For a reference parameter (or out in C#), reflection will copy the new value into the object array at the same position as the original parameter. You can access that value to see the changed reference.

public class Example {
  public static void Foo(ref string name) {
    name = "foo";
  }
  public static void Test() {
    var p = new object[1];
    var info = typeof(Example).GetMethod("Foo");
    info.Invoke(null, p);
    var returned = (string)(p[0]);  // will be "foo"
  }
}
like image 129
JaredPar Avatar answered Sep 30 '22 05:09

JaredPar