I have been searching about creating a new object within a loop, found some answers and topics but its way too hard to understand. Making it with lists and arrays etc.
What I am trying to do is, get an input from the user(lets say 3), and create objects as many as the user will with the unique names. Like newperson1, newperson2, newperson3 etc.
My code looks like this:
class person
{
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
for (int i = 0; i < p; i++)
{
person newperson = new person();
}
}
}
Is there any way to create new objects with following numbers in the end of the object name? Thanks!
Edit:
My new code looks like this; I was more thinking like this:
class Persons
{
//Person object id
public int id { get; set; }
//Persons name
public string name { get; set; }
//Persons adress
public string adress { get; set; }
//Persons age
public int age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int count = int.Parse(Console.ReadLine());
var newPersons = new List<Persons>(count);
for (int i = 0; i < count; i++)
{
newPersons[i].id = i;
Console.Write("Write name for person " + i);
newPersons[i].name = Console.ReadLine();
Console.Write("Write age for person " + i);
newPersons[i].age = int.Parse(Console.ReadLine());
Console.Write("Write adress for person " + i );
newPersons[i].adress = Console.ReadLine();
}
Console.WriteLine("\nPersons \tName \tAge \tAdress");
for (int i = 0; i < count; i++)
{
Console.WriteLine("\t" + newPersons[i].name + "\t" + newPersons[i].age + "\t" + newPersons[i].adress);
}
Console.ReadKey();
}
}
I understand that I have to create object with arrays or lists. But I didn't really understand how I will access them after they are created person by person..
You CAN use a loop. The trick is that you have to save the reference to each one as you create it. A simple way would be to use an array. You have to declare the array outside the loop, then use your loop counter as the index into the array...
for(var x = 1; x<=10; x++){ var Object + x = new Object(); };
Creating objects in a loop is always valid. It is very common too.
No, the main method only runs once when you run your program. It will not be executed again. So, the object will be created only once.
It's fairly advanced to create dynamic classes (where the actual name of the object is different). In other words, it's WAY harder to do what you're asking than to create a List or an Array. If you spend an hour or two studying Collections, it will pay off in the long run.
Also, you might consider adding a Name
property to your Person
class, and then you can set that differently for each person you create.
As others have said, you will need to store them in an array or list:
public class Person
{
public string Name { get; set; }
}
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
var people = new List<Person>();
for (int i = 0; i < p; i++)
{
// Here you can give each person a custom name based on a number
people.Add(new Person { Name = "Person #" + (i + 1) });
}
}
Here's an example of one way to access a Person
from the list and let the user update the information. Note that I've added a few properties to the Person
class:
public class Person
{
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public string Address { get; set; }
public int Age
{
// Calculate the person's age based on the current date and their birthday
get
{
int years = DateTime.Today.Year - DateOfBirth.Year;
// If they haven't had the birthday yet, subtract one
if (DateTime.Today.Month < DateOfBirth.Month ||
(DateTime.Today.Month == DateOfBirth.Month &&
DateTime.Today.Day < DateOfBirth.Day))
{
years--;
}
return years;
}
}
}
private static void GenericTester()
{
Console.Write("How many persons you want to add?: ");
string input = Console.ReadLine();
int numPeople = 0;
// Make sure the user enters an integer by using TryParse
while (!int.TryParse(input, out numPeople))
{
Console.Write("Invalid number. How many people do you want to add: ");
input = Console.ReadLine();
}
var people = new List<Person>();
for (int i = 0; i < numPeople; i++)
{
// Here you can give each person a custom name based on a number
people.Add(new Person { Name = "Person" + (i + 1) });
}
Console.WriteLine("Great! We've created {0} people. Their temporary names are:",
numPeople);
people.ForEach(person => Console.WriteLine(person.Name));
Console.WriteLine("Enter the name of the person you want to edit: ");
input = Console.ReadLine();
// Get the name of a person to edit from the user
while (!people.Any(person => person.Name.Equals(input,
StringComparison.OrdinalIgnoreCase)))
{
Console.Write("Sorry, that person doesn't exist. Please try again: ");
input = Console.ReadLine();
}
// Grab a reference to the person the user asked for
Person selectedPerson = people.First(person => person.Name.Equals(input,
StringComparison.OrdinalIgnoreCase));
// Ask for updated information:
Console.Write("Enter a new name (or press enter to keep the default): ");
input = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(input))
{
selectedPerson.Name = input;
}
Console.Write("Enter {0}'s birthday (or press enter to keep the default) " +
"(mm//dd//yy): ", selectedPerson.Name);
input = Console.ReadLine();
DateTime newBirthday = selectedPerson.DateOfBirth;
if (!string.IsNullOrWhiteSpace(input))
{
// Make sure they enter a valid date
while (!DateTime.TryParse(input, out newBirthday) &&
DateTime.Today.Subtract(newBirthday).TotalDays >= 0)
{
Console.Write("You must enter a valid, non-future date. Try again: ");
input = Console.ReadLine();
}
}
selectedPerson.DateOfBirth = newBirthday;
Console.Write("Enter {0}'s address (or press enter to keep the default): ",
selectedPerson.Name);
input = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(input))
{
selectedPerson.Address = input;
}
Console.WriteLine("Thank you! Here is the updated information:");
Console.WriteLine(" - Name ............ {0}", selectedPerson.Name);
Console.WriteLine(" - Address ......... {0}", selectedPerson.Address);
Console.WriteLine(" - Date of Birth ... {0}", selectedPerson.DateOfBirth);
Console.WriteLine(" - Age ............. {0}", selectedPerson.Age);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With