dragonfly02
dragonfly02

Reputation: 3679

How to use Activator.CreateInstance to reflect a type whose constructor parameter differs only by ref

How to use reflection to create an instance of the type below while calling a specific constructor? Checked all the overloads of Activator.CreateInstance but don't think there is a match for this. In the example below, I want x to be doubled after an instance of SomeType is created, namely, I want the constructor taking the ref int version to be called.

Also, how does MS define the 'best match' algorithm for CreatInstance method?

internal sealed class SomeType
{

    //consturctor with non-reference parameter
    public SomeType(int x)
    {
        x *= 3;
    }

   //constructor with reference parameter 
    public SomeType(ref int x)
    {
        x *= 2;
    }
}

class Program 
{
     private static void main()
     {
        var param = new object[] {4}; // constructor parameter
        Console.WriteLine("Param Before consturctor called: " + param[0]);
        Object instance = Activator.CreateInstance(typeof(SomeType), param);
        Console.WriteLine("Param after constuctor called: " + param[0]);
     }
}

Upvotes: 3

Views: 1627

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149598

In order to match the ref int x parameter, you can create an instance using Type.GetConstructor and passing it an System.Int32& as a parameter:

var ctor = typeof(SomeType).GetConstructor(new[] { Type.GetType("System.Int32&") });
var constructorParameters = new object[] { 1 };
SomeType someType = (SomeType)ctor.Invoke(constructorParameters);

Edit:

As @mikez suggested, it is even better to use typeof(int).MakeByRefType() instead of System.Int32&:

var ctor = typeof(SomeType).GetConstructor(new[] { typeof(int).MakeByRefType(); });
var constructorParameters = new object[] { 1 };
SomeType someType = (SomeType)ctor.Invoke(constructorParameters);

Upvotes: 3

Related Questions