Anders Würtz wrote:
i have an assignment to iterate through a collection containing
different types of numeric values (float, double, int, byte, short etc.)
and to add 1 to all of them. I tried with array and arraylist so far,
but i either get a cast exception or the value doesn't seem to get
updated at all. What should i be doing to make it work?
Thanks in advance
There are lots of ways to do this, I'm not sure what they are teaching
you at present. If you *know* each one of them is a value type, you can
just convert them all to a given super-type (like double) and add to
them.
Otherwise, you could do something like this:
ArrayList a = new ArrayList();
int i = 1;
float f = 2.0f;
double d = 3.0;
byte b = 4;
string s = "hello";
// Add some data to the array.
a.Add( i );
a.Add( f );
a.Add( d );
a.Add( b );
a.Add( s );
// Print them out to show
foreach ( object o in a )
Console.Out.WriteLine("value: {0}", o );
// Increment those we can increment.
for ( int o=0; o<a.Count; ++o )
{
// Can't convert non-value types
if ( a[o].GetType().IsValueType )
{
// Make it a double
double d1 = (double)Convert.ChangeType( a[o], d.GetType() );
// Increment it
d1 += 1.0;
// Make it what it was.
object obj = Convert.ChangeType( d1, a[o].GetType() );
// And store it back in the array
a[o] = obj;
}
}
// Print them out to show
foreach ( object o in a )
Console.Out.WriteLine("value: {0}", o );
This isn't pretty and it isn't elegant. But it should get you started.
Matt