Bi.
Bi.

Reputation: 1906

Create a class with array of objects

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!

Upvotes: 8

Views: 113311

Answers (1)

Nick Craver
Nick Craver

Reputation: 630607

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.

Upvotes: 15

Related Questions