JensOlsen112
JensOlsen112

Reputation: 1299

Calling empty default constructor of type

I'm trying to instantiate every property (of type JobVmInput) on my object. This is my code so far:

var properties = this.GetType().GetProperties();

foreach (var p in properties)
{
     var type = p.PropertyType;
     if (type.IsSubclassOf(typeof(JobVmInput)))
     {
          var constructor = type.cons.GetConstructor(**what to input here**);
          p.SetValue(p, constructor.Invoke(**what to input here**));
     }
}

However I don't know what to input in the GetConstructor and constructor.Invoke methods. I've looked at the MSDN documentation but I'm quite uncertain in regards to what they accept. I just want to call the empty default constructor.

Upvotes: 2

Views: 1498

Answers (1)

Selman Genç
Selman Genç

Reputation: 101680

You can use:

var constructor = type.GetConstructor(Type.EmptyTypes);
p.SetValue(this, constructor.Invoke());

Or:

p.SetValue(this, Activator.CreateInstance(type));

Note that I have replaced first parameter to this since the SetValue method expects an instance of your object not the PropertyInfo

Upvotes: 5

Related Questions