raz
raz

Reputation: 13

Java clone() in C#

I'm rewriting code from Java to C#. I have a problem with clone function in C#.

Code in Java:

public Tour(ArrayList tour)
{
    this.tour = (ArrayList) tour.clone();
}

My code in C#:

public Tour(List<City> tour)
{
    //What I should do here?
}

I tried some techniques of cloning in C# but without results.

EDIT:

This solution works perfectly:

this.tour = new List<City>();
tour.ForEach((item) =>
{
     this.tour.Add(new City(item));
});

Greetings!

Upvotes: 0

Views: 1281

Answers (2)

dav_i
dav_i

Reputation: 28107

The java.util.ArrayList.clone() returns a shallow copy of this ArrayList instance (i.e the elements themselves are not copied).
--Source

To do the same thing in .NET's List<T> you can do:

var newList = oldList.ToList();

Upvotes: 2

toadflakz
toadflakz

Reputation: 7944

You should be implementing ICloneable on your City class.

That way you can do this:

public List<City> Tour {get; private set;}

public Tour(List<City> tour)
{
    this.Tour = new List<City>();
    foreach (var city in tour)
      this.tour.Add((City)city.Clone());    
}

Upvotes: 1

Related Questions