7

Given the following sample code;

class Program
{
    static void Main(string[] args)
    {
        var results = GetChildren().ToList();
    }

    static IEnumerable<MyBaseClass> GetChildren()
    {
        return Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(t => t.BaseType == typeof(MyBaseClass))
            .Select(o => (MyBaseClass)Activator.CreateInstance(o, null));
    }
}

abstract class MyBaseClass
{ }

class MyChildClass : MyBaseClass
{
    public MyChildClass(object paramOne)
    {

    }
}

I'm receiving the following error;

MissingMethodException: Constructor on type 'CreateInstanceCtorIssue.MyChildClass' not found.

However, if I add a parameterless constructor, it creates the objects OK.

I'm trying to work out why the parameter I'm suppying to CreateInstance is not causing it to find the correct constructor. Anyone got any ideas?

1
  • 1
    This should work: Activator.CreateInstance(o, (object)null) Commented Feb 29, 2012 at 14:46

2 Answers 2

10

Basically, the second argument of the method you are calling is a params array. What's happening is that the C# compiler is treating your method-call as though you are passing this argument in using the "unexpanded" form, i.e. by passing a null array-reference. On the other hand, your intent is to use the "expanded" form, i.e. pass a reference to an array containing a single null-reference.

You can coax the compiler to do what you want like this:

// Unexpanded:
Activator.CreateInstance(o, new object[] { null })

// Expanded explictly:
Activator.CreateInstance(o, (object) null )
Sign up to request clarification or add additional context in comments.

1 Comment

That was indeed the issue, thank you very much. I had just assumed that the compiler would interpret the null that I was passing as part of the params array, which is obviously incorrect when you think about it. Cheers!
3

You have to pass the constructor parameters:

.Select(o => (MyBaseClass)Activator.CreateInstance(o, new object[] { someParam }));

MyChildClass expects a single parameter of type object for its constructor - you have to pass this parameter within an array.

2 Comments

Please answer why you have to pass it within an array. The params nature of the second parameter of CreateInstance suggests that one should not have to pass in an array.
agree. needs some explanation. normally you wouldn't have to qualify a a params explicitly as a [] but simply pass in param1, param2. That's after all why params exist, so why is it necessary here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.