C# Collections (Obj to Numericupdown convertions)

Started by
2 comments, last by dhammer 16 years, 4 months ago
I'm looking for a means to create a collection of numericupdown objects and then easily extract their properties (Value and Name) by using a Foreach loop which will cycle through each object in the collection. Right now I'm using ArrayList because it stores objects pretty easily but I'm having trouble pulling my information out of it after the fact. I end up pulling a Object out of the ArrayList but can't seem to convert it back to NumericUpDown type in order to view the Value and Name properties of that object. This is the code that i am having trouble with. The line, "n_UpDn = obj; is obviously an improper convertion from object to numericupdown.
[source=lang="c#"]
StringBuilder stats = new StringBuilder();
NumericUpDown n_UpDn;

//Stat_Objs is an ArrayList with NumericUpDns added to it
foreach (Object obj in Stat_Objs)
{
    n_UpDn = obj;
    if (n_UpDn.Value > 0)
        stats.Append(n_UpDn.Name.ToString() + "+" + n_UpDn.Value.ToString()):
}

Advertisement
You need to do a cast, "n_UpDn = (NumericUpDown)obj;".

However if you have access to .Net 2.0 or above, the use of "Object" is considered bad practice. You should be using a generic List(System.Collections.Generic.List) instead of an ArrayList.
Two better ways.

// This works with .Net 2.0 and above.// First use List instead of a list array.  This just shows you the list.List<NumericUpDown> Stat_Objs = new List<NumericUpDown>();// Then your stuff with a few changes.StringBuilder stats = new StringBuilder();// You don't need this any more.// NumericUpDown n_UpDn;foreach (NumericUpDown n_UpDn in Stat_Objs){    n_UpDn = obj;    if (n_UpDn.Value > 0)        stats.Append(n_UpDn.Name.ToString() + "+" + n_UpDn.Value.ToString()):}


// Now if you are stuck with .Net 1.x or still want to use the ArrayList you can do this.StringBuilder stats = new StringBuilder();//We still don't need this.//NumericUpDown n_UpDn;//The foreach loop actually does the cast for you.  So you don't need to treat it as an "object".foreach (NumericUpDown n_UpDn in Stat_Objs){    n_UpDn = obj;    if (n_UpDn.Value > 0)        stats.Append(n_UpDn.Name.ToString() + "+" + n_UpDn.Value.ToString()):}


theTroll
Thank you for your helpful information.

This topic is closed to new replies.

Advertisement