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.
The Activator. CreateInstance method creates an instance of a type defined in an assembly by invoking the constructor that best matches the specified arguments. If no arguments are specified then the constructor that takes no parameters, that is, the default constructor, is invoked.
CreateInstance(ActivationContext, String[]) Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data. CreateInstance(Type) Creates an instance of the specified type using that type's parameterless constructor.
The Activator. CreateInstance method creates an instance of a specified type using the constructor that best matches the specified parameters. For example, let's say that you have the type name as a string, and you want to use the string to create an instance of that type.
An alternative is:
object obj = System.Runtime.Serialization.FormatterServices
.GetUninitializedObject(t);
which creates the object in memory but doesn't run any constructor. Scary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With