Using reflection to invoke a constructor that takes a ref parameter

Recently in the MSDN Forums, someone wanted to know how he could use reflection to invoke a constructor that took a ref parameter. Personally I can’t think of any reason why a constructor would have a ref parameter, and try as I did I could not dig up that thread (neither Google nor MSDN forum search returns the right thread in the search results).

Anyway his main issue was that he did not know how to get the type of a ref string argument. C# will not let you do typeof(string&) which is what he wanted. The solution was to use Type.GetType("System.String&"). In case anyone ever has this bizarre requirement, here’s a small sample that shows how this can be done.

class A
{
    public A(){}

    public A(ref string id)
    {
        id = "AAA";
    }
}

class B
{
    public B(){}

    public B(ref string id)
    {
        id = "BBB";
    }
}

class Program
{
    static void Main()
    {
        new Program().Foo();
    }

    private void Foo()
    {
        string s = "SSS";
        Console.WriteLine(s);
        Bar(typeof(A), ref s);
        Console.WriteLine(s);
        Bar(typeof(B), ref s);
        Console.WriteLine(s);
    }

    private void Bar(Type type, ref string s)
    {
        var ctor = type.GetConstructor(
          new Type[] { Type.GetType("System.String&") });
        var arr = new object[] { s };
        ctor.Invoke(arr);
        s = (string)arr[0];
    }
}

Note how I have to copy back the string from the object array. This is because while the string is passed by ref, it’s the reference in the array that’s passed to the constructor – and not the string that was passed as a parameter to the Bar method. The difference may be subtle unless you think about it.

Advertisements

5 thoughts on “Using reflection to invoke a constructor that takes a ref parameter

  1. Thank you very much.

    The last paragraph regarding copying the string from the object array is key. That is the key I’ve been searching for.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s