Howdy all,
I am wondering how to populate an array during runtime..somewhat like Visual Basic has ReDim().
Code:
public int[] values;
values[0] = 1;
values[1] = 2;
//etc..
Any help would be great...
Phreak
Printable View
Howdy all,
I am wondering how to populate an array during runtime..somewhat like Visual Basic has ReDim().
Code:
public int[] values;
values[0] = 1;
values[1] = 2;
//etc..
Any help would be great...
Phreak
You could use an ArrayList (System.Collections), or you could create a custom strongly typed collection (code from an app I'm busy writing, easily modified to cater for int's):
Code:public class GroupCollection: CollectionBase
{
#region Constructor
public GroupCollection()
{
// Default constructor.
}
#endregion
#region Indexer
/// <summary>
/// Gets or sets the Group item at the specified index
/// </summary>
public Group this[int index]
{
get
{
return (Group) List[index];
}
set
{
List[index] = value;
}
}
#endregion
#region Add
/// <summary>
/// Adds the specified Group item to the collection.
/// </summary>
/// <param name="value">The Group instance to add.</param>
/// <returns>The index the item was added to.</returns>
public int Add(Group value)
{
return List.Add(value);
}
#endregion
#region IndexOf
/// <summary>
/// Returns the index at which the specified value exists.
/// </summary>
/// <param name="value">The value to return the index of.</param>
/// <returns>The index at which the value exists.</returns>
public int IndexOf(Group value)
{
return List.IndexOf(value);
}
#endregion
#region Insert
/// <summary>
/// Inserts the specified Group at the passed index.
/// </summary>
/// <param name="index">The index at which the Group must be inserted at.</param>
/// <param name="value">The Group instance to add.</param>
public void Insert(int index, Int16 value)
{
List.Insert(index, value);
}
#endregion
#region Remove
/// <summary>
/// Removes the specified Group instance from the collection.
/// </summary>
/// <param name="value">The Group instance to remove.</param>
public void Remove(Group value)
{
List.Remove(value);
}
#endregion
#region Contains
/// <summary>
/// Returns whether the Group instance is contained in the collection.
/// </summary>
/// <param name="value">The Group instance to check for existance in the collection.</param>
/// <returns>If the Group instance exists in the collection.</returns>
public bool Contains(Group value)
{
// If value is not of type Group, this will return false.
return List.Contains(value);
}
#endregion
#region OnInsert
protected override void OnInsert( int index, Object value )
{
if (value.GetType() != Type.GetType("ServFTP.Classes.Group") )
throw new ArgumentException("Value must be of type ServFTP.Classes.Group", "value");
}
#endregion
#region OnRemove
protected override void OnRemove(int index, Object value)
{
if (value.GetType() != Type.GetType("ServFTP.Classes.Group") )
throw new ArgumentException("Value must be of type ServFTP.Classes.Group", "value");
}
#endregion
#region OnSet
protected override void OnSet(int index, Object oldValue, Object newValue)
{
if (newValue.GetType() != Type.GetType("ServFTP.Classes.Group") )
throw new ArgumentException("Value must be of type ServFTP.Classes.Group", "value");
}
#endregion
#region OnValidate
protected override void OnValidate(Object value)
{
if (value.GetType() != Type.GetType("ServFTP.Classes.Group") )
throw new ArgumentException("Value must be of type ServFTP.Classes.Group", "value");
}
#endregion
}
C# has no support for dynamic arrays and similar functions like ReDim(). All arrays must be set at compile time, however, an ArrayList works similar to a vector in C++ in that, it is a completely dynamic array.
That isn't true. I can declare an array in code with an N count using a variable, so in a way, you can create your own Redim code if you wanted to by doing something like this:Quote:
All arrays must be set at compile time
Create a new array of the new size.
Copy over the contents from the old array into the new one (that is if you want to preserve it)
Return the new array.
You would call it like:
myArray = ReDimFunction(myArray, 10, blnPreserve)
Of course, this is inefficient, but it is a way to do it. I think generics will help us when using Arraylists because we can strongly type the lists. At least, that is my understanding.
Thanks for the replies. I only asked for this because the user of my application will be setting the values. There isn't a set amount they can have, and by declaring the bounds at design time, I would think it would use much more memory than needed (user could have 2, or 200 values). But I'll take your replies into concideration, thanks again :D
Phreak
If thats the case the can do what hellswraith said. Use a text box to get the number of items to be created, then you can just declare the array. Here is an example.Quote:
Originally posted by «°°phReAk°°»
Thanks for the replies. I only asked for this because the user of my application will be setting the values. There isn't a set amount they can have, and by declaring the bounds at design time, I would think it would use much more memory than needed (user could have 2, or 200 values). But I'll take your replies into concideration, thanks again :D
Phreak
Code:private void btnCreate_Click(object sender, System.EventArgs e)
{
int i = Convert.ToInt32(txtAmount.Text);
string[] names = new string[i];
for (int index = 0; index < names.Length; index++)
{
names[index] = "name " + index;
}
foreach (string str in names)
{
MessageBox.Show(str);
}
}
It's exactly what VB does though...Quote:
Of course, this is inefficient, but it is a way to do it.
I thought that would be what it does, but I wasn't sure if there was some other method they used that I wasn't aware of.Quote:
Originally posted by CornedBee
It's exactly what VB does though...
I recommend making you own collection class or using ArrayList
I always wondered how VB did that....
Code:public void IncStringArray(string[] &aray, bool preserve)
{
if (preserve == false)
{
aray = new string[aray.length + 1];
}
else
{
string[] temp = new string[aray.length + 1];
Array.Copy(aray, temp, aray.length - 1);
aray = new string[temp.length];
Array.Copy(temp, aray, temp.length - 2);
}
}
I know I'm possibly being rude now, but I consider most people here to be above the average, so don't take offense :)Quote:
Originally posted by Magiaus
I recommend making you own collection class or using ArrayList
I always wondered how VB did that....
Does the average VB user even know about the intricacies of data structures? Would the AVBU care if he's using continous-memory list, linked list, double-ended queue list, binary search tree or hash map?
There's a thread in "Code it better" about a C# user who didn't have a clue about that, resulting in his algorithm being about 100 times slower than it ought to be, until I bashed some sense into him ;)
Your right of course the average VB programmer would not care at all. I really whish I had never used VB it makes me stupid sometimes.
What was the programmer doing that was slowing thier algarithm down so much?
I'm actually getting ready to go back to school to take classes in c and c++ because there are just somethings I can't seem to get straight...
example
That always returns the same address for objects of the same type. I was, for fun trying to use CopyMemory in C++, and I came across this problem. Do you know how to fix it, CornedBee? I haven't got a clue as to what to try to get the right address unless I use the frameworlks Marshalling some how but I would rather know how it works and not be a VB programmer :)Code:public __gc class Helpers
{
public:
public static System::IntPtr AddressOf(System::Object* o)
{return new __nogc System::IntPtr(&o);}
}
Sorry, no idea of the unsafe workings of C#. I prefer to use C++, then I don't have to use exotic stuff just to make simple things work :)
The programmer was collecting colors or something from an image. Just read the thread, should be in a search for "binary tree" in Code It Better.
Technically his code is C++.NET ;) but either way I don't think you'll ever be able to do that in C++ just because you'd have a serious casting problem in C++ since you have the generic Object in .NETQuote:
Originally posted by CornedBee
Sorry, no idea of the unsafe workings of C#.
I use templates for that kind of stuff.
eww templates are gross. I figured it would never work it was more or less just a test to see what would happen. I was working on a C++ .net wrap of WIN32API. I wrapped about 90 api calls and the supporting structs and constant but I decieded it was pointless to try and do a complete wrap or even a nearly complete wrap because the further I got the more it started to look like the unsafe classes used by the framework, and some things like CopyData just made my head spin so bad it wasn't funny. Also allot of the api wouldn't work unless I implemented Marshaling in the framework and that was what I was trying to avoid that and having to open a header ans convert api if I needed it.
Average... Define Average I would say I am "Average VB User" but i've written more multi-threaded more appz in VB than I care to recall at the moment...Quote:
Originally posted by CornedBee
Does the average VB user even know about the intricacies of data structures?
I'm sure the "average" VB user does not concern himself with such things he merely concerns himself with how many buttons he shall have to write more than 4 lines of code to make thier back-end.Quote:
Originally posted by CornedBee
Would the AVBU care if he's using continous-memory list, linked list, double-ended queue list, binary search tree or hash map?
HOWEVER, I did say I was an average user simply because I only use VB for making custom Apps for business like inventory progs and such but serveral times I've written programs with HUGE Standard Deviation calculations inside of them that HAD to be multi-threaded... as a result I HAD to concern myself with the memory I was using...
Quote:
Average... Define Average
Code:av·er·age
n.
Mathematics.
A number that typifies a set of numbers of which it is a function.
See arithmetic mean.
An intermediate level or degree: near the average in size.
The usual or ordinary kind or quality: Although the wines vary, the average is quite good.
Sports. The ratio of a team's or player's successful performances such as wins, hits, or goals, divided by total opportunities for successful performance, such as games, times at bat, or shots: finished the season with a.500 average; a batting average of.274.
Law.
The loss of a ship or cargo, caused by damage at sea.
The incurrence of damage or loss of a ship or cargo at sea.
The equitable distribution of such a loss among concerned parties.
A charge incurred through such a loss.
Nautical. Small expenses or charges that are usually paid by the master of a ship.
adj.
Mathematics. Of, relating to, or constituting an average.
Being intermediate between extremes, as on a scale: a player of average ability.
Usual or ordinary in kind or character: a poll of average people; average eyesight.
Assessed in accordance with the law of averages.
v. av·er·aged, av·er·ag·ing, av·er·ag·es
v. tr.
Mathematics. To calculate the average of: average a set of numbers.
To do or have an average of: averaged three hours of work a day.
To distribute proportionately: average one's income over four years so as to minimize the tax rate.
v. intr.
To be or amount to an average: Some sparrows are six inches long, but they average smaller. Our expenses averaged out to 45 dollars per day.
Phrasal Verbs:
average down
To purchase shares of the same security at successively lower prices in order to reduce the average price of one's position.
average up
To purchase shares of the same security at successively higher prices in order to achieve a larger position at an average price that is lower than the current market value.
--------------------------------------------------------------------------------
[From Middle English averay, charge above the cost of freight, from Old French avarie, from Old Italian avaria, duty, from Arabic ‘awrya, damaged goods, from ‘awr, blemish, from ‘awira, to be damaged. See wr in Semitic Roots.]
--------------------------------------------------------------------------------
aver·age·ly adv.
aver·age·ness n.
Synonyms: average, medium, mediocre, fair, 1middling, indifferent, tolerable
These adjectives indicate a middle position on a scale of evaluation. Average and medium apply to what is midway between extremes and imply both sufficiency and lack of distinction: a novel of average merit; an orange of medium size. Mediocre stresses the undistinguished aspect of what is average: “The caliber of the students... has gone from mediocre to above average” (Judy Pasternak). What is fair is passable but substantially below excellent: in fair health. Middling refers to a ranking between average and mediocre: gave a middling performance. Indifferent suggests neutrality: “His home, alas, was but an indifferent attic” (Edward Everett Hale). Something tolerable is merely acceptable: prepared a tolerable meal.
What about this for redimming...
Write a lib in VB that contains a function that accepts and returns an array. Pass in the array you want to redim and also the new bounds you want to give it and then redim preserve (yada) in VB and return the freshly resized array. Would that work?
I think that would work if you din't mind the extrea lib..... I like hellswraiths answer though. Even if ReDimming an array has some overheade issues unless you have a huge ind like 999,999,999 the extra procces ticks needed are not even worth talking about on the machines we have today. Yeah that old AS 400 might not like a bunch of resizing arays but let's face it redim is a wide used and wide spread tool. Every Script language does it or damn near every one. And it's very handy.
I have to say there are some old school asm and c++ programmers that say it is ineficiant just because it is not because it's wrong to do or even that they never would do it. The trick is knowing if a resized array is the answer you need or if something else would do the trick. I don't know about linked lists and so on so I honestly couldn't say what would be the best way to go. I do know that an Array list functions like an array but it support the add and insert members which let you be free of the worry of a fixed index. It also seems to be Microsfts answer to the I need a variable sized array. MSDN recommends it's use to solve this problem. Does that mean it is effecient? No. It means it will do the job without having to write any extra code except.