5

Consider this code:

class Program
{
    static void Main(string[] args)
    {
        var instance = Activator.CreateInstance<Person>();//No parameterless constructor defined for this object.

    }
}

public class Person
{
    public Person(string name = "Shahrooz") { }
}

When use this code: Activator.CreateInstance<Person>();I get this error:

No parameterless constructor defined for this object.

Note that my constructor has default parameter:string name = "Shahrooz"

Why we can not create instance from a class that has constructor,despite the constructor has default value parameter?

0

1 Answer 1

8

We can not create instance from a class that has constructor because the constructor still needs one parameter, even though it is defaulted. You can get the default value, though, by calling GetParameters() and accessing the initial element:

ConstructorInfo constr = typeof(Person).GetConstructor(new[] {typeof(string)});
ParameterInfo p0 = constr.GetParameters()[0];
object defaultValue = p0.DefaultValue;
Person p = (Person)constr.Invoke(new[] {defaultValue});
// ...or using Activator
Person p = (Person)Activator.CreateInstance(typeof(Person), defaultValue);
Sign up to request clarification or add additional context in comments.

3 Comments

But why we can create by this code: object o = Activator.CreateInstance(typeof(Person), "Ali");
because the method requires array of objects/parameters
@ShahroozJefriㇱ You can do that because you pass the parameter explicitly. The generic version of Create<T> requires a parameterless constructor, which is not the same as a constructor will all its parameters defaulted to some values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.