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?
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:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With