adding one element to a fixed array []

  • Thread starter Thread starter damian
  • Start date Start date
D

damian

This is my first time posting so I hope i'm in the right place.
I have a project which uses an xsd.exe generated .cs file containing
the class definitions for each of my schema's XML elements.
I am using this stucture in memory to maintain my data, but I have
come across the problem that becuase it uses a fixed array [] and not
an arraylist, it is a bit tricky to manage.
I could modify the generated .cs file but the schema is large and if
the schema changes in the future it would mean reworking it, this does
not seem like the best solution.
So at the moment I have a function like this to add an element to the
array: It does not seem like the most elegant solution. I was
wondering if anyone else had come across this problem. Note
that ..ServiceTable is a property so i can't send it as a ref.

private void NewService(object sender, EventArgs e)
{
ServiceType[] s = ESGMain.ESG.ServiceTable;
Array.Resize(ref s, s.Length + 1);
ESGMain.ESG.ServiceTable = s;
s[s.Length - 1] = new ServiceType();
s[s.Length - 1].serviceID = newServiceID;
}

thanks in advance
 
An array is always of a fixed length. If you want to use a longer array, you
must build a new array and copy all of the elements from the original array
into it, which is what Array.Resize does.

--
HTH,

Kevin Spencer
Microsoft MVP
Software Composer
http://unclechutney.blogspot.com

I had the same problem once. Fixed it using the same solution.
 
I used to fight this battle regularly when using the SOAP/WSE proxies;
if you are doing something similar, then note that WCF allows you
(easily) to either use generated classes (as before), or use a shared
entity assembly on both sides of the wire; this means that your
collections stay collections, etc, and you get to use your component
model on both sides.

Of course, it means you need to be stricter about deciding which logic
goes in which classes (i.e. the shared entity classes shouldn't
contain database code; that should be in a server-only adapter), but
it helps. It also means that you can use the same validation at both
client and server (which is a good thing) while also allowing for the
possibility of ad-hoc callers via generated proxies.

Marc
 
Back
Top