Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a class with array of objects

Tags:

c#

Code below defines a ChargeCustomer class that contains an array of type "customers". I want to be able to create an object with either 1 "customer" or 2 "customers" based on the constructor parameters. Is this the right way to do so in C#:

public class ChargeCustomer 
{
    private Customer[] customers;

    public ChargeCustomer( string aName, string bName, int charge )
    {
        customers = new Customer[2];
        customers[0] = new Customer(aName, charge);
        customers[1] = new Customer(bName, charge);  
    }

    public ChargeCustomer( string bName, int charge )
    {
        customers = new Customer[1];
        customers[0] = new Customer( bName, charge );
    }

}

Thanks!

like image 358
Bi. Avatar asked Apr 17 '10 00:04

Bi.


People also ask

How do you create an array of objects in class?

An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.

Can we create array of objects in Java?

Answer: Yes. Java can have an array of objects just like how it can have an array of primitive types. Q #2) What is an Array of Objects in Java? Answer: In Java, an array is a dynamically created object that can have elements that are primitive data types or objects.

Can we create array of objects in C++?

Array of Objects in c++ Like array of other user-defined data types, an array of type class can also be created. The array of type class contains the objects of the class as its individual elements. Thus, an array of a class type is also known as an array of objects.


1 Answers

Note: This assumes that DropBox was a mis-paste in the original question.

You can move things around and have 1 constructor using params for any number of names, like this:

public class ChargeCustomer 
{
  private Customer[] customers;

  public ChargeCustomer( int charge, params string[] names)
  {
    customers = new Customer[names.Length];
    for(int i = 0; i < names.Length; i++) {
      customers[i] = new Customer(names[i], charge);
    }
  }
}

Using this approach you just pass the charge first and any number of customer names, like this:

new ChargeCustomer(20, "Bill", "Joe", "Ned", "Ted", "Monkey");

It will create an array the correct size and fill it using the same charge for all, and 1 Customer per name by looping through the names passed in. All that being said, there's probably a much simpler overall solution to your problem, but without making changes outside the Customer class (aside from the constructor calls), this would be the simplest approach/smallest change.

like image 130
Nick Craver Avatar answered Sep 22 '22 07:09

Nick Craver