Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# create object dynamically and set each parameter with loop

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading