Search code examples
dynamicconstructorc#-4.0internal

Passing a dynamic attribute to an internal constructor


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.


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...)