Reputation: 923
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?
Upvotes: 5
Views: 12492
Reputation: 151594
MyClass2
only has the default, parameterless constructor. It doesn't inherit the MyClass(int)
constructor.
Upvotes: 0
Reputation: 60493
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).
Upvotes: 5
Reputation: 171178
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.
Upvotes: 3