Reputation: 1684
I'm trying to create an instance of a class in my CoreCLR app, but when I call Activator.CreateInstance, I get a System.MissingMethodException saying that it can't find a constructor on the class it's trying to create. The class indeed has a constructor. What am I doing wrong?
The project is only targeting dnxcore50.
This is the code:
using System;
namespace MyNamespace
{
public class Program
{
public void Main(string[] args)
{
Activator.CreateInstance(typeof (MyClass), true);
}
}
public class MyClass
{
public MyClass() { }
}
}
And this is the exception:
System.MissingMethodException was unhandled by user code
HResult=-2146233069
Message=Constructor on type 'MyNamespace.MyClass' not found.
Source=mscorlib
StackTrace:
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
at MyNamespace.Program.Main(String[] args) in C:\projects\coreclrplayground\InvokeMember\src\InvokeMember\Program.cs:line 9
InnerException:
Upvotes: 2
Views: 2270
Reputation: 42030
On CoreCLR, Activator
doesn't have an overload accepting a boolean parameter indicating whether non-public constructors can be used to instantiate the type.
Your snippet builds correctly because the compiler chooses the CreateInstance(Type type, params object[] args)
overload, which treats your boolean like a constructor parameter: since your constructor is parameterless, an exception is thrown.
Upvotes: 3