5

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..

7
  • Where are the other two }s? Commented Dec 6, 2014 at 19:44
  • Please use Upper Camel Case for class names, e.g. class Person. Commented Dec 6, 2014 at 19:52
  • Also, you want an array or List. It's not "way too hard", it is how you program with homogeneous collections of objects, not by giving them different names. Commented Dec 6, 2014 at 19:54
  • 1
    What are you trying to achieve? List and arrays are basic concepts of programming, it shouldn't be difficult for understanding and using. Commented Dec 6, 2014 at 19:54
  • Thank you for all the comments and tips, I appreciate it. I will think about the naming next time :) I'm still a newbie, arrays and lists are not that hard but I don't know how to combine them yet, it's helpful of you anyway thank you very much! :) Commented Dec 6, 2014 at 20:25

6 Answers 6

7

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

The closest thing to doing what you are asking is to create a dictionary:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var dictionary = new Dictionary<string, Person>();

        Console.Write("How many persons you want to add?: ");
        int p = int.Parse(Console.ReadLine());

        for (int i = 0; i < p; i++)
        {
            dictionary.Add("NewPerson" + i, new Person());
        }

        // You can access them like this:
        dictionary["NewPerson1"].Name = "Tim Jones";
        dictionary["NewPerson2"].Name = "Joe Smith";
    }

    public class Person
    {
        public string Name {
            get; 
            set;
        }
    }
}

2 Comments

Keep in mind that the OP indicated that arrays were "way too hard". I don' think introducing dictionaries is going to help any.
@JonathonReinhart - Yes, but as you pointed out in your comment above, there are not "way too hard". They are fundamental.
1

You can create dynamically named variables in C#.

What you need is a collection of persons:

var persons = new List<person>();

for (int i = 0; i < p; i++)
{
   persons.Add(new person());
}

1 Comment

@Christos technically it's possible you can create dynamic assemblies, classes, methods in C#. but in this situation it isn't worth to mention it. it would just cause confusion
0

Arrays and List are basic building blocks. they should't be very hard. but if you don't want to deal with them try creating a method whose responsibility is to give you your new objects given count.

static void Main(string[] args)
    {
        Console.Write("How many persons you want to add?: ");
        int p = int.Parse(Console.ReadLine());

        var newPersons = CreatePersons(p);

         foreach (var person in newPersons)
         {
             Console.WriteLine("Eneter age for Person :" person.Name);
             person.Age = Console.ReadLine();
         }

    }

    static IEnumerable<Person> CreatePersons(int count)
    {
        for (int i = 0; i < count; i++)
        {
            yield return new Person{ Name="newPerson" +1 };
        }
    } 

Comments

0

Try this one.

I am creating Person (Object) as array first (like creating object array)

Then I am assigning that to the Person Class.

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);
        Persons[] newPersons = new Persons[count];

        for (int i = 0; i < count; i++)
        {
            newPersons[i] = new Persons();
            newPersons[i].id = i+1;
            Console.Write("Write name for person " + (i+1) + "\t");
            newPersons[i].name = Console.ReadLine();
            Console.Write("Write age for person " + (i + 1) + "\t");
            newPersons[i].age = int.Parse(Console.ReadLine());
            Console.Write("Write adress for person " + (i + 1) + "\t");
            newPersons[i].adress = Console.ReadLine();
        }

        Console.WriteLine("\nPersons Name \tAge \tAdresss \n");
        for (int i = 0; i < count; i++)
        {
            Console.WriteLine(newPersons[i].name + "\t\t" + newPersons[i].age + "\t" + newPersons[i].adress);
        }

        Console.ReadKey();
    }
}

Comments

0

If you want to iterate through an array of object in C#, you need to define the ToString() method (override) and after that, you can use the ToString() method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.