parhine
parhine

Reputation: 123

How can I create lots of objects with different property values?

I'm programming in C# and I want to instantiate lots of new objects to my application, all of the same type, but with different values for their properties. Example:

Student student1 = new Student();
student1.Name = "James";
student1.Age = 19;
student1.City = "Los Angeles";

Student student2 = new Student();
student2.Name = "Karen";
student2.Age = 20;
student2.City = "San Diego";

Student student3 = new Student();
student3.Name = "Bob";
student3.Age = 20;
student3.City = "Dallas";

This way of coding seems really wrong to me because what if I didn't need 3, but 500 students? What would be the best way to do it then?

I tried to use a for loop for this but that doesn't work because the property values differ.

What is the most efficient way to do this?

Thanks in advance.

Upvotes: 2

Views: 973

Answers (6)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

If you want 500 students I suggest extracting data to a file, database etc. student1..student499 implementation looks very ugly: let's organize them into array: Student[] students. As an example, let's use the simplest csv file Students.csv solution in the format

name,age,city

E.g.

name,age,city
James,19,Los Angeles
Karen,20,San Diego
Bob,20,Dallas

Having the file completed you can easily read it:

  using System.IO;
  using System.Linq;
  ...

 Student[] students = File
   .ReadLines("Students.csv")
   .Where(line => !string.IsNullOrWhiteSpace(line)) // Skip empty lines
   .Skip(1)  // Skip header
   .Select(line => line.Split(','))   
   .Select(items => new Student() {
      Name = items[0],
      Age = int.Parse(items[1]),
      City = items[2], })
   .ToArray();

Upvotes: 0

user3797387
user3797387

Reputation:

Programming is not about typing data. Need a lot of data? - Load them from files, databases, servers, through GUI, etc.

You can make a handy constructor, you can make factories and builders, but they are not for creating hundreds of objects in a row. Even if it is historical data, one day you will want to change them, fix something in them. Believe me, it's much easier to separate them from the code and store somewhere else, than to edit hundreds of lines of code later.

Upvotes: 0

InBetween
InBetween

Reputation: 32750

Well, it depends what you are going to use it for. If it’s for testing, then you could use a custom built tool to create random Students:

public class RandomStudentCreator
{
    private readonly Random rnd = new Random();
    private readonly IList<string> cities, names;
    private readonly int minAge, maxAge;

    public RandomStudentCreator(
        IList<string> names,
        IList<string> cities,
        int minimumInckusiveAge,
        int maximumExclusiveAge)
    {
         //Argument validation here
         this.cities = cities;
         this.names = names;
         minAge = minimumInckusiveAge;
         maxAge = maximumExclusiveAge;
    }

    public Student Next()
    {
        var student = new Student();
        student.Name = names[rnd.Next(names.Count);
        student.City = cities[rnd.Next(cities.Count);
        Student.Age = rnd.Next(minAge, maxAge);
    }
}

If this is production code, then you should be creating students based on:

  1. User input
  2. Some data backend (DB, text file, etc.)

But in any case, you don’t want to create a variable for each student. You probably want a collection of students. Depending on what you want to do with them, the type of collection you need may vary, the framework gives you plenty of options:

  1. Arrays: Student[]
  2. Lists: List<Student>
  3. Queues: Queue<Student>
  4. Stacks: Stack<Student>
  5. Sets: HashSet<Student>
  6. Etc.

And last but not least, you probably want to implement a constructor in Student that takes a name, city and age to make instantiation a little bit more compact than what you currently have:

public class Student
{
    public Student(string name,
                   int age,
                   string city)
    {
        Name = name;
        Age = age;
        City = city;
    }

    //...
}

var john = new Student(“John”, 19, “LA”);

Upvotes: 0

Igor Zhurba
Igor Zhurba

Reputation: 157

Add constructor to Student like this

Student (string name, int age, string city)
{
    Name = name;
    Age = age;
    City = city;
}
///
Student student1 = new Student("James", 19, "Los Angeles");

Upvotes: 1

Crowcoder
Crowcoder

Reputation: 11514

In order to do anything with your objects at runtime you will probably want them in a list.

Without reading from a file or database, etc., the most concise way might be :

var Students = new List<Student>{
    new Student { Name = "Bob", Age = 22, City = "Denver"  },
    new Student { Name = "Sally", Age = 33, City = "Boston"  },
    new Student { Name = "Alice", Age = 12, City = "Columbus"  }
};

I don't know your end goal however, is this just mock data, like for a test?

Upvotes: 3

Marcelo Myara
Marcelo Myara

Reputation: 3011

Well, if what you mean by more efficient way to do it is just to write less code, you could instanciate them assigning the property's values at once, just like:

Student student1 = new Student() { Name = "James", Age = 19, City = "Los Angeles" };

If you want not just to write less code, but to - let's say - read the data from another source (like a Json list, or a TXT file) you will have to write a loader for it.

Upvotes: 0

Related Questions