Alex Rivera | Logout

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

Asked 2010-03-23T15:26:44.413
23

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.

[EDIT] I'm sorry but I misread the actual code... The sample I provided doesn't illustrate it. I accepted JonH answer because it provided a good piece of information.

Edit
Report

1 Answer

0

This may not be feasible for you to do, but the simplest thing is to pass the argument list after the type like so:

Activator.CreateInstance(t, "name");

You'll want to think about what f() is really trying to do. Should it be instantiating an object of type A at all? What other classes will it instantiate?

One possibility is to have a switch statement within f() which passes the correct parameters to CreateInstance() for class A. This won't scale, but that may not be an issue for you.

answered 2010-03-23T15:45:48.863

Your Answer