I have two classes like these.
public class MyClass
{
protected readonly int SomeVariable;
public MyClass(){}
public MyClass(int someVariable)
{
SomeVariable = someVariable;
}
}
public class MyClass2 : MyClass {}
Is there a way to create an instance of the class using Activator.CreateInstance? I wrote something like this:
public class ActivatorTest<TViewModel>
where TViewModel : MyClass
{
public void Run()
{
var viewModel = Activator.CreateInstance(typeof(TViewModel), new Object[] {2}) as TViewModel;
}
}
new ActivatorTest<MyClass2>().Run();
But I had an exception Constructor on type 'MyClass2' not found.
Any ideas?
on this line
var viewModel = Activator.CreateInstance(typeof(TViewModel), new Object[] {2,3}) as TViewModel;
you try to add two int parameters to your ctor here : new Object[] {2,3}
And there's no ctor taking two parameters (in the shown code).
There is no constructor on that class that takes two integers as arguments. Add such a constructor or correct the arguments that you pass in.
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