Constructor on type '###' not found
Solution 1
Works fine in .NET 4.5, and even 2.0
using System;
class SmaSeries
{
public SmaSeries(ISeries<decimal> parent, int periods,
TierKind? runOnTier = null) { }
static void Main()
{
object[] args = new object[]
{
new DecimalSeries(),
20,
new Nullable<TierKind>(TierKind.Client)
};
object obj = Activator.CreateInstance(typeof(SmaSeries), args);
}
}
enum TierKind { Client }
interface ISeries<T> { }
class DecimalSeries : ISeries<decimal> { }
I think perhaps: is your constructor or one of the types maybe not public?
Solution 2
Sure enough it was a bug. I was creating List of Object in order to dynamically add parameters and then just forgot to do ToArray when calling the activator, and since the args is params object[], it took the list instead of taking its members. Sorry for wasting your time and thanks to all who replied/commented on this post.
user1044169
Updated on June 16, 2022Comments
-
user1044169 almost 2 years
I have a type that accepts these parameters:
public SmaSeries(ISeries<decimal> parent, int periods, TierKind? runOnTier = null)
I am trying to create an instance of this type using Activator.CreateInstance (the overload that accepts type and args) by passing object[] in the args parameter:
new object[] { new DecimalSeries(), 20, new Nullable<TierKind>(TierKind.Client) } //DecimalSeries implements ISeries<decimal>
Getting back Constructor on type 'SmaSeries' not found.
Is there a way to fix the args so the activator finds the constructor?
Thanks.
-
Alex Mendez over 11 yearsI don't think 2.0 allows specifying default values on parameters.
-
Marc Gravell over 11 years@AlexMendez actually, it does... I'm talking about the .NET platform 2.0, not the C# compiler. The attribute used has been there forever, courtesy of VB.NET; if you use a later compiler version to target an earlier .NET version, it works fine. How
Activator.CreateInstance
works is entirely down to the .NET version (not the C# version). What you are talking about (optional parameters) is largely a compiler feature, not a runtime feature (although it is a bit more complex than that... isn't everything) -
Alex Mendez over 11 yearsI knew about VB, but did not know you could compile with the later compiler to 2.0 and still use default values in parameters in c#. Also, I don't think I said anything about optional parameters. It was default values on parameters. Good to know. Thanks.
-
Marc Gravell over 11 years@AlexMendez optional parameters, and parameters with default values, are basically synonymous
-
Oleg Sakharov over 10 yearsMate, you just saved me from few hours of debugging.