5

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?

Denis
  • 833
  • 3
  • 12
  • 22
  • 1
    You're passing arguments to the constructor, but there is no constructor that takes 2 arguments. That's what the error is telling you. – Reactgular Jul 15 '14 at 15:24
  • 1
    I've used up my close vote for "offtopic - typo" (which I retracted), but your question seems to be a duplicate of [C# Activator createInstance for extending class](http://stackoverflow.com/questions/12113131/c-sharp-activator-createinstance-for-extending-class). – CodeCaster Jul 15 '14 at 15:37
  • Related post - [Constructor on type not found](https://stackoverflow.com/q/25577601/465053) – RBT Apr 17 '18 at 11:33

3 Answers3

5

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).

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
3

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.

usr
  • 168,620
  • 35
  • 240
  • 369
0

MyClass2 only has the default, parameterless constructor. It doesn't inherit the MyClass(int) constructor.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272