Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# reflection to call a constructor

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?

like image 548
scatman Avatar asked Jul 15 '10 12:07

scatman


People also ask

Why C is used today?

The C programming language doesn't seem to have an expiration date. It's closeness to the hardware, great portability and deterministic usage of resources makes it ideal for low level development for such things as operating system kernels and embedded software.

Is C hard to learn?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


2 Answers

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 });
    }
}

EDIT: 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.

like image 141
Jon Skeet Avatar answered Oct 14 '22 16:10

Jon Skeet


Yes, you can use Activator.CreateInstance

like image 26
Ben Voigt Avatar answered Oct 14 '22 15:10

Ben Voigt