8

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!

2
  • Does DropBox derive from Customer? If not, you can't store it in a Customer array. Commented Apr 17, 2010 at 0:34
  • that is correct, however, you are limited to only be able to create 1 or 2 customers. Commented Apr 17, 2010 at 1:25

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.