How to change attributes of an ArrayList?

M

mb

If an ArrayList has an object named "myTest" which has properties ".Name"
and ".Number". now how do I change the .Name of the object in the
arraylist?

I have had bad experiences so far with ArrayLists. It seem like a lot of
extra work to get value out of the ArrayList. Maybe I am doing it wrong.

Thanks for the help.
 
S

Stefan Holdermans

MB,

MB> If an ArrayList has an object named "myTest" which has properties
MB> ".Name" and ".Number". now how do I change the .Name of the
MB> object in the arraylist?

using System;
using System.Collections;

class Test {
public string Name;
public int Number;

public static void Main() {
Test myTest = new Test() ;
ArrayList myList = new ArrayList();

myList.Add(myTest);

((MyTest) myList[0]).Name = "MB";
((MyTest) myList[0]).Number = 7 ;

Console.Write(myTest.Name) ;
Console.Write(myTest.Number);
}
}

HTH,

Stefan
 
M

mb

I guess that will work. It's funny, none of the books I have looked at show
how to do this. In my experience so far, ArrayLists are cumbersome and
awkward. Are they supposed to be like this?
 
S

Scott Allen

On one hand an ArrayList is flexible, because you can stuff any type
of object into an arraylist for storage. It's getting the object back
out and manipulating the object as a specific type that is indeed
awkward. Some people will try to get rid of the awkwardness by
creating thier own strongly typed container classes (i.e. a class that
would only store Test instances, and only return Test instances), but
this involves additional code. Generics, in .NET 2.0, will make the
process much easier:
http://msdn.microsoft.com/msdnmag/issues/03/09/NET/

--
Scott
http://www.OdeToCode.com/

I guess that will work. It's funny, none of the books I have looked at show
how to do this. In my experience so far, ArrayLists are cumbersome and
awkward. Are they supposed to be like this?

Stefan Holdermans said:
MB,

MB> If an ArrayList has an object named "myTest" which has properties
MB> ".Name" and ".Number". now how do I change the .Name of the
MB> object in the arraylist?

using System;
using System.Collections;

class Test {
public string Name;
public int Number;

public static void Main() {
Test myTest = new Test() ;
ArrayList myList = new ArrayList();

myList.Add(myTest);

((MyTest) myList[0]).Name = "MB";
((MyTest) myList[0]).Number = 7 ;

Console.Write(myTest.Name) ;
Console.Write(myTest.Number);
}
}

HTH,

Stefan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top