vendredi 11 mars 2022

Is there a way to build a new object feeding it properties step by step in a loop in C#?

I am working on a user administrative system and I came across the situation where I want the user to fill out all the properties of a user type they selected before.

Because the amount and type of properties differ depending on the selected type I am trying to build the object dynamically from a loop, where I would print the respective property name and the user needs to enter the input for this property.

Is there any way to collect all the entered input and build the respective object afterwards?

I already thought of using a simple list and feeding the constructor all the properties inside, but I am not sure if this is even correct or if there is an easier solution.

var typeInput = Console.ReadLine();
var myType = typeof(User).Assembly.GetType("Entities." + typeInput);

if (myType == null) throw new TypeLoadException("User type '" + typeInput + "' not found, check your input!");
        
Console.WriteLine("Please fill out the following properties: ");

foreach (var prop in myType.GetProperties())
{
   Console.Write(prop.Name + ": ");
   var propValue = Console.ReadLine();
}




Aucun commentaire:

Enregistrer un commentaire