C# Activator.CreateInstance MissingMethod exception
Question
I'm trying to create instances of objects that have the same base type like this:
Assembly myAssembly = Assembly.GetExecutingAssembly();
var objs = myAssembly.GetTypes().Where(t => t.BaseType == typeof(SearchLogicObjectBase)).OrderBy(o => o.FullName);
foreach (var item in objs)
{
SearchLogicObjectBase p = (SearchLogicObjectBase)Activator.CreateInstance(item.GetType(), new Object[] { false });
_searchlogic.AddDefaultSearchObject(p);
}
The derived objects have constructors like this:
public SearchLogicCsri()
: this(true)
{ }
public SearchLogicCsri(bool extendsearch)
: base(extendsearch)
{
Table = "csri";
ViewModel = "CsriViewModel";
ExtendSearch = extendsearch;
}
and the base object (SearchLogicObjectBase) has a constructor like this:
public SearchLogicObjectBase(bool extendsearch)
{
_extendsearch = extendsearch;
}
However, the above code results in the following exception:
Constructor on type 'System.RuntimeType' not found.
Both the base and derived types have a constructor that takes a single boolean so I'm not sure why I get the error.
Can anyone help please?
Solution
Do not pass item.GetType() but item, since item is already a type.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow