Activator.CreateInstance(Type) for a type without parameterless constructor
- by Seb
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.