Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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.

like image 578
Seb Avatar asked Mar 23 '10 15:03

Seb


People also ask

Does activator CreateInstance call constructor?

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.

What is activator CreateInstance?

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.

What is activator CreateInstance in net core?

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.


1 Answers

An alternative is:

object obj = System.Runtime.Serialization.FormatterServices
          .GetUninitializedObject(t);

which creates the object in memory but doesn't run any constructor. Scary.

like image 85
Marc Gravell Avatar answered Sep 21 '22 02:09

Marc Gravell