how can create new object of the class from user input? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

how can create new object of the class from user input?

hi, I want to know is there any way to instantiate object from user input, something like this: PERSON p1= new PERSON(); and my concept: (which doesn't work 😁) PERSON console.readline() = new PERSON();

29th Jul 2019, 10:51 PM
Mahdi Mohebali
Mahdi Mohebali - avatar
2 Answers
+ 11
Jake Nice code snippet for someone who claims their "knowledge of C# is miniscule..." 😉 Here's a refinement of the Main method. https://code.sololearn.com/c20FJ7ZEyJnp/ static void Main(string[] args) { var people = new List<Person>(){ new Person(Console.ReadLine()), new Person(Console.ReadLine()) }; people.ForEach( p => Console.Write(
quot;{p.name} ") ); } ----
30th Jul 2019, 9:16 AM
David Carroll
David Carroll - avatar
+ 4
Well my knowledge of C# is miniscule but perhaps you can keep a list of people objects and assign a name to each object through a constructor that can be assigned through input? The following is an example of two separate Person objects added to a people list and given a name through input: static void Main(string[] args) { var people = new List<Person>(); //person 1, name assigned through input and added to list Person p = new Person(Console.ReadLine()); people.Add(p); //person 2, name assigned through input and added to list (can add as many as youd like) p = new Person(Console.ReadLine()); people.Add(p); //print names of person 1 and person 2 Console.Write(people[0].name + " " + people[1].name); } } class Person { public string name; public Person(String name) { this.name = name; } }
29th Jul 2019, 11:19 PM
Jake
Jake - avatar