What method in Reflection can give me an empty class instance?

    2 answers 2

    Activator.CreateInstance

    var instance = (ObjectType)Activator.CreateInstance(typeof(ObjectType)); 
    • Thank you for help - Vladislav

    There is a slightly different way to create an instance, an example of Generic is a method for creating an instance of an object of a given type:

     public static T GetNewObject<T>() { var constructor = typeof(T).GetConstructor(new Type[] {}); if (constructor != null) { return (T) constructor.Invoke(new object[] {}); } return default(T); } 

    Unlike Activator.CreateInstance , this method will not throw an exception, if non-parametric constructors are not defined for the object, the value null will be returned.

    Source link: Get a new object instance from a Type - there are other answers that will be useful, but I decided to select this one.

    Type.GetConstructor Method — Searches for an open instance constructor whose parameters correspond to the types contained in the specified array.

    MethodBase.Invoke method - calls a method or constructor represented by the current instance, using the specified parameters.

    The default (T) expression is a default value expression that creates a default value of type T

    Of course, using the approach using Activator.CreateInstance is much simpler and more convenient, as already answered by @free_ze

    • one
      As it turns out, Activator is faster - Andrew NOP
    • @AndreyNOP reflection has always been a bit slow. - Denis Bubnov