Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor on type '' not found

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?

like image 220
Denis Avatar asked Mar 19 '23 01:03

Denis


2 Answers

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

like image 140
Raphaël Althaus Avatar answered Mar 28 '23 12:03

Raphaël Althaus


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.

like image 34
usr Avatar answered Mar 28 '23 10:03

usr