Dynamic arrays of object members
A reader wrote to me and asked how to create an array of object members, but where the size of the array is known only at runtime. In other words, the size of the array is not know until after the user is running the program.
For example, suppose you have a class named clsData and within that class is a property named distributionList. Because you know you eventually want an array of this property, somewhere in scope you would write:
clsData.distributionList[] myList;
Note that you have declared a variable named myList, you have not defined it. This means that the rvalue of myList is null because no memory has actually been allocated for the array. All you have is variable named myList that is capable of pointing to an array of distributionList members.
Now, sometime later after you have determined the number of elements you need in the array (e.g., size), you can write:
myList = new clsData.distributionList[size];
This statement is a data definition because Windows now goes out and grabs enough memory to hold size elements of a distributionList member.
__________________
Jack Purdum, Ph.D.
Author: Beginning C# 3.0: Introduction to Object Oriented Programming (and 14 other programming texts)
|