tr**************@yahoo.com wrote:
Hi all
i am having application in c#.
I want to create array of class object at runtime.
I don't want to set array bound at design time.
How to set array bound at runtime and how to access array element?
Can some one help me.
Thanks in advance.
I will assume I understand your questions. If not, please give us more
information and repost.
To construct an array:
Type <varname> = new Type[<length>];
example:
Int32[] values = new Int32[10];
// values now has indices 0 through 9 (10 elements)
To construct an array that doesn't start at index 0, you need to use a
method of the Array object:
Int32[] values = (Int32[])Array.CreateInstance(typeof(Int32),
new Int32[] { 10 }, new Int32[] { 1 });
// values now has indices 1 through 10
To store a value into the array:
values[5] = 23;
to retrieve a value from the array, just use values[x] wherever you need
to read the value at index x:
Int32 someValue = values[9];
If you want to resize the array, if that's what your question is, then
you need to allocate a new array of the new, correct, size, then copy
the elements from the old array to the new and replace the reference in
the variable with the new array, something like this (using the first,
0-based, example as a start):
Int32[] values = new Int32[10];
....
// "resize" to 20 elements
Int32[] newValues = new Int32[20];
Array.Copy(values, newValues, values.Length);
values = newValues;
Also, note that arrays containing objects (like class instances,
strings, etc.) as opposed to value types (Int32, DateTime, Boolean,
etc.) are defaulted to null, which means there are no objects stored in
the array to begin with. This means that the following will crash with a
null-reference exception:
String[] names = new String[10];
Int32 len = names[0].Length; // crash here, names[0] = null
Hope this answers some of your questions.
--
Lasse Vågsæther Karlsen
http://www.vkarlsen.no/
mailto:la***@vkarlsen.no
PGP KeyID: 0x2A42A1C2