Why do I need Type.MakeByRefType()?

This was asked on one of our DLs. Basically, the question is, "I am trying to invoke a method that takes a reference to a structure (i.e. void MyMethod(ref TimeSspan span) ) - how do I create this type so that I can call the method?".

The answer is that you do not need to do that. .NET will take care of all the stuff that happens behind the scenes for you. So in the following example, you can see that you don't really need to do know if the parameter is reffed or not:

class Program

{

       static void Main(string[] args)

       {

              Type type = typeof(TimeSpan);

              Type refType = type.MakeByRefType();

              MethodInfo i = typeof(Program).GetMethod("Method");

              object[] oo = new object[] { TimeSpan.FromSeconds(2) };

              i.Invoke(null, oo);

              Console.WriteLine(oo[0].ToString());

       }

       public static void Method(ref TimeSpan span)

       {

              span = TimeSpan.FromSeconds(1);

       }

}

An interesting point to note - you have to use the array you pass in to interrogate the result of the ByRef parameter. You can't just use any boxed value since .NET will replace that item in the array. In other words, the following invocation wont work as you expect (the value returned in the byref parameter will be lost):

object o = TimeSpan.FromSeconds(2);

i.Invoke(null, new object[] { o });

So why do I need the MakeByRefType() method?

Well, consider the previous example, but lets add a new method to the class:

public static void Method(TimeSpan span)

{

       return;

}

Now the call to GetMethod() will fail saying that there is an ambigous method. So now you need to use the GetMethod() call that takes arguments to solve the ambiguity. When you do that, and you want to get the method with the ref parameter, you will need to use Type.MakeByRef() to create a Type you can use in that call.

Note: Type.MakeByRef()   is a new method in 2.0. It does not exist in 1.1 - if you need to do this in 1.1, use the Type.GetType() and append the "&" symbol to the type you want to create a ByRef for.