Activator.CreateInstance(Type) for a type without parameterless constructor

Posted by Seb on Stack Overflow See other posts from Stack Overflow or by Seb
Published on 2010-03-23T15:26:44Z Indexed on 2010/03/23 15:33 UTC
Read the original article Hit count: 401

Filed under:
|

Reading existing code at work, I wondered how come this could work. I have a class defined in an assembly :

[Serializable]
public class A
{
    private readonly string _name;
    private A(string name)
    {
        _name = name;
    }
}

And in another assembly :

public void f(Type t) {
    object o = Activator.CreateInstance(t);
}

and that simple call f(typeof(A))

I expected an exception about the lack of a parameterless constructor because AFAIK, if a ctor is declared, the compiler isn't supposed to generate the default public parameterless constructor.

This code runs under .NET 2.0.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about c#