steve
steve

Reputation: 25

Dynamically build an array for web service

I'm using C# and asp.net to query a web service.

The user will enter the number of guests and then I need to add that number of guests to the web service call. Creating the guests manually like this works.

// Create room layout for searching

Guest adult = new Guest();
adult.Id = 1;
adult.Title = "Mr";
adult.Firstname = "Test";
adult.Surname = "Test";

Guest adult2 = new Guest();
adult2.Id = 2;
adult2.Title = "Mr";
adult2.Firstname = "Test";
adult2.Surname = "Test";

Guest[] adults = new Guest[] { adult,adult2 };

The user chooses the number of adults on my sites search page, I do not know the number of adults and want to be able to add them dynamically to the web service call. I will be recieving the number of adults like this

int numberofguests = Convert.ToInt32(search.Guest);

I have tried numerous ways of doing it, but can't get it to work

Upvotes: 1

Views: 6603

Answers (5)

JaredPar
JaredPar

Reputation: 754505

Instead of using a raw array why not use ArrayList or List<Object>?

var list = new List<Guest>();
adult.Id = 1;
adult.Title = "Mr";
adult.Firstname = "Test";
adult.Surname = "Test";
list.Add(adult);

Guest adult2 = new Guest();
adult2.Id = 2;
adult2.Title = "Mr";
adult2.Firstname = "Test";
adult2.Surname = "Test";
list.Add(adult2);

Guest[] adults = list.ToArray();

Upvotes: 2

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

I suggest you use a List<Guest>. You can initialize the size with the number of guests when you create it, but that is really just an optimization. If you want to add more guests later, you can do that and the List will resize as necessary.

List has a ToArray() method if you want to turn the list into an array for some reason.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499760

All the other answers have suggested using List<Guest> and normally I'd agree - but in this case there's really no need as it seems you know the size beforehand:

Guest[] guests = new Guest[numberOfGuests];
for (int i=0; i < numberOfGuests; i++)
{
    Guest guest = new Guest();
    // Fill in information about the guest here
    // based on the web form
    guests[i] = guest;
}

That's not to say you shouldn't use a List<Guest> if that's more convenient in any way - it's just that the (probably) biggest benefit of using a List<T> is that you don't need to know the size in advance. As that's not relevant here (unless I'm missing something) there's not as much reason to use a list.

Upvotes: 2

Steve
Steve

Reputation: 8511

I'd suggest using a List rather than an array in this case. You can convert it to an array once it is populated if you still need it as an array.

Upvotes: 2

Randolpho
Randolpho

Reputation: 56381

List<Guest> guests = new List<Guest>();
for(int i=0; i<numberOfGuests; i++)
{
  guests.Add(new Guest()
  {
    Title = "Mr",
    Firstname = "Test",
  });
}
return guests.ToArray();

Upvotes: 6

Related Questions