Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an instance of the internal constructor with parameters using Reflection?

I have a different scenario. I need to create instance of a class which is public but having all its constructors as internal. The class has no default constructor.

I tried the below ways, but it didn't work.

Activator.CreateInstance(typeof(ClassName));
Activator.CreateInstance(typeof(ClassName), nonpublic:true);
Activator.CreateInstance(typeof(ClassName),true);
Activator.CreateInstance(typeof(ClassName), new object[]{double,bool});

I also tried this, but ended up with System.MissingMethodException.

var constructors = typeof(ClassName).GetConstructors();
foreach(var ctor in constructors)
    ctor.Invoke(new object[] {double, bool});

I am not able to use BindingFlags in Xamrarin. I am stuck, does anyone have a solution for this?

like image 579
Harikrishnan Avatar asked Jul 15 '15 09:07

Harikrishnan


1 Answers

I found the solution by myself. Here is what I did.

ConstructorInfo info = typeof(ClassName).GetTypeInfo().DeclaredConstructors.First();
ClassName e = info.Invoke(new object[] { parameters }) as ClassName;

I hope this might help someone. Cheers:)

like image 163
Harikrishnan Avatar answered Oct 22 '22 09:10

Harikrishnan