118

I have the following scenario:

class Addition{
 public Addition(int a){ a=5; }
 public static int add(int a,int b) {return a+b; }
}

I am calling add in another class by:

string s="add";
typeof(Addition).GetMethod(s).Invoke(null, new object[] {10,12}) //this returns 22

I need a way similar to the above reflection statement to create a new object of type Addition using Addition(int a)

So I have string s= "Addition", I want to create a new object using reflection.

Is this possible?

2
  • 3
    Why do you want to use reflection ? Reflection comes with a performance penalty, creates maintenances issues on the long run... Commented Jul 15, 2010 at 13:03
  • 35
    @Patrick, there are many cases where the performance penalty can be ignored as long as the user goal is achieved. Commented Jul 15, 2010 at 15:19

2 Answers 2

207

I don't think GetMethod will do it, no - but GetConstructor will.

using System;
using System.Reflection;

class Addition
{
    public Addition(int a)
    {
        Console.WriteLine("Constructor called, a={0}", a);
    }
}

class Test
{
    static void Main()
    {
        Type type = typeof(Addition);
        ConstructorInfo ctor = type.GetConstructor(new[] { typeof(int) });
        object instance = ctor.Invoke(new object[] { 10 });
    }
}

Yes, Activator.CreateInstance will work too. Use GetConstructor if you want to have more control over things, find out the parameter names etc. Activator.CreateInstance is great if you just want to call the constructor though.

Sign up to request clarification or add additional context in comments.

14 Comments

Yes, but then you have to implement all the overload resolution rules to pick the right constructor. Whereas the runtime will do it for you if you call msdn.microsoft.com/en-us/library/wcxyzt4d.aspx
So GetConstructor is preferred if you want to cache a delegate (performance enhancement when calling the same constructor many times), but for one-off use Activator would be easier.
@AkshayJoy: "its ot working" isn't nearly enough information. I've told you how to go about converting it mechanically - another alternative would be to make sure you understand the C# code and then make sure you know the VB syntax for constructing an array. Without wishing to be mean, if that's too much of a challenge then you should really really stay away from reflection.
Got it Thanks Jon Skeet Dim params(0) As Type params(0) = GetType(FViewer) Dim constructorInfoObj As ConstructorInfo = objType.GetConstructor(params)
@SarathAvanavu: You wouldn't do that with reflection anyway... it's not clear what situation you're talking about, so it may be worth asking a new question (after searching for similar ones, of course).
|
57

Yes, you can use Activator.CreateInstance

4 Comments

This really needs to be a proper answer
Interestingly, it seems that when constructors have parameters, then reflection is faster than Activator.CreateInstance: gist.github.com/KallDrexx/d08a60f2d807673af1d9e90e07d61aeb
@KallDrexx: Your benchmark is not measuring the cost of reflection correctly, because most of it is being done outside the measured function. Move the typeof(Program).GetConstructor(new[] {typeof(int)}); inside the function that calls it to have a fairer comparison. And even then, you have chosen the exact matching overload ahead of time, while Activator has to do overload resolution across all constructors with the same number of parameters.
@BenVoigt while true, if you refresh you will see a new test where I did add this test case. Even with considering the timing of GetConstructor() call it still is 2/3rds the time of an ACtivator.CreateInstance. I also don't think it's unreasonable for Activator.CreateInstance to cache any reflection calls it may incur (since it's reasonable it may be called again) but whatever its cost is it apparently doesn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.