Search code examples
c#arraysweb-serviceswsdlgeneric-list

Is there any difference between using Arrays or converting a list to an Array in C# when sending to a web service method?


This question may be similar to already answered once, but my question is about sending either Array or List.ToArray() to the web service's method when it accepts Array of Objects.

So, here is the question:

I need to send Array of Programs to a web service.

By service definition, the Main Object, that I need to send to a web service has the following wsdl type:

<xsd:element name="Pgms" type="ns1:ArrayOfPrograms" nillable="true" minOccurs="0"/>

Is there any difference between the following codes:

1st Option:

List<string> programList = insertRow["programName"].ToString().Trim().Split(',').ToList();
Program [] programArray = new Program[programList.Count];
foreach(var program in programList)
{
      Program programObj = new Program();
      programObj.Item1 = item1;
      programObj.Item2 = program.ToString().Trim();
      for(int i = 0; i <= programList.Count; i++)
      { 
          programArray[i] = programObj;
      }
}

webserviceMethod.send(mainObject);

2nd Option:

List<string> programList = insertRow["programName"].ToString().Trim().Split(',').ToList();
List<Program> programList = new List<Program>();
foreach(var program in programList)
{
     Program programObj = new Program();
     programObj.Item1 = item1;
     programObj.Item2 = program.ToString().Trim();
     programList.Add(programObj);
}
programList.ToArray();
webserviceMethos.send(mainObject);

Which option do I need to use to send to the service?


Solution

  • A List is backed by an array. Populating an array T[] by looping through a list or calling ToArray() on a List<T> will result in the same thing an object T[] at the end.

    Personally I prefer adding items to a list then calling to array but either method will work.

    There are however multiple issues with both of the examples you provide which may actually be where the issues lie, not in which method will yield an array to send to a web service.