Best way to clone an ArrayList?

  • Thread starter Thread starter Chris Bellini
  • Start date Start date
C

Chris Bellini

I was just looking for some opinions on the best way to clone an
ArrayList object. For example, if class A contains an ArrayList, what
would be the best way to make a copy of it for class B (but not using
the class constructors):

class A
{
public A()
{
// constructor stuff goes here
}

public void DoStuff()
{
ArrayList arrTPB = new ArrayList();

arrTPB.Add("Ricky");
arrTPB.Add("Julian");
arrTPB.Add("Bubbles");

// new B object
B myB = new B();

// copy arrTPB from class A to arrNames of myB
// ???
}
}


class B
{
public ArrayList arrNames;

public B()
{
arrNames = new ArrayList();
// other constructor stuff goes here
}
}

Thanks in advance.



Chris
 
hi,

i'm not sure if i understood the question properly but couldnt you just copy
and paste the class?
 
Reply in text:

Chris Bellini said:
I was just looking for some opinions on the best way to clone an ArrayList
object. For example, if class A contains an ArrayList, what would be the
best way to make a copy of it for class B (but not using the class
constructors):

class A
{
public A()
{
// constructor stuff goes here
}

public void DoStuff()
{
ArrayList arrTPB = new ArrayList();

arrTPB.Add("Ricky");
arrTPB.Add("Julian");
arrTPB.Add("Bubbles");

// new B object
B myB = new B();

// copy arrTPB from class A to arrNames of myB
// ???
myB.PutNames(arrTPB);
}
}


class B
{
public ArrayList arrNames;

public B()
{
arrNames = new ArrayList();
// other constructor stuff goes here
}

public PutNames(ArrayList al)
{
foreach (object obj in ArrayList)
{
if (!obj is string)
continue;
arrNames.Add(obj);
}
}
 
Obvious, yet slick. Thx :)


Chris

Howard said:
Reply in text:




public PutNames(ArrayList al)
{
foreach (object obj in ArrayList)
{
if (!obj is string)
continue;
arrNames.Add(obj);
}
}
 
You might buy a little performance by using the AddRange method. I think it
still iterates over the collection, but the allocation would be done all at
once.
 
Back
Top