Question

Calling an internal constructor with a dynamic argument in C# 4.0b results in the following exception

System.ArgumentNullException: Value cannot be null. Parameter name: constructor

Example code (thanks to Jon Skeet)

public class Test
{
    internal Test(string x)
    {
    }

    static void Main()
    {
        dynamic d = "";
        new Test(d);
    }
}

It seems the runtime does not consider internal constructors when it's trying to pick the right one. This seems to be a bug, so I posted it on Connect: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=472924

It seems they fixed it for the new version.

Was it helpful?

Solution

EDIT: Okay, I've now tracked it down a lot further - it's using an internal constructor that causes a problem.

Here's a really short but complete example which demonstrates the problem:

public class Test
{
    internal Test(string x)
    {
    }

    static void Main()
    {
        dynamic d = "";
        new Test(d);
    }
}

I suggest you log this with Connect - then post the URL here and we can vote on it :)

(My guess is that inside the DLR there's a call to GetConstructor without the appropriate BindingFlags.NonPublic, but that's just a guess...)

OTHER TIPS

Without seeing the code I would suggest that you are passing a non-instantiated class to your constructor. Ensure that they are within scope and have been instantiated e.g. by use of new, before they are passed to your non-dynamic object.

Edit

On seeing your code I would suggest that you use DynamicObject rather than dynamic for your helper costructor and Entity property.

Edit after seeing Jon's answer

I think that the problem is in using the GetEntity() method to generate the dynamic object instance.

I note that Jon creates an instance of MyDynamicObject within the same scope as he uses it.

I assume that you're generating an instance of your object within the GetEntity() method, in which case it is no longer inscope when you come to use it, being classed as a local object.

Using "MyDynamicObject e = entity;" will force the compiler to imlicitly use the MyDynamicObject constructor and map your result to it. Hence address space is already allocated and in scope to be used when passing it to the Helper constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top