Home > Mobile >  C# create object dynamically and set each parameter with loop
C# create object dynamically and set each parameter with loop

Time:07-30

Is there any way to fill up the variables of a dynamically created instance?

Something like:

var generatedRow = Activator.CreateInstance(listTables[typeToAdd]);

foreach (PropertyInfo prop in generatedRow.GetType().GetProperties())
{
    generatedRow.prop = 1;
}

NOTE: The code below is not meant to work, it's just an idea of what I want to achieve.

CodePudding user response:

you can use the prop variable to set the value of the object that you created using the Activator.

    public class Car {
        public string Name {get;set;}
        public string Color {get;set;}
    }

    var carType = typeof(Car);
    
    var carInstance = Activator.CreateInstance(carType);
    
    foreach (PropertyInfo prop in carInstance.GetType().GetProperties())
    {
        prop.SetValue(carInstance, Guid.NewGuid().ToString());
    }
    
    
    //DEMOSTRATION ONLY
    Console.WriteLine(((Car)carInstance).Name);
    Console.WriteLine(((Car)carInstance).Color);
  • Related