|
How to copy one element of a Generic Collection?
I need to copy one element of a generic collection and add it to the list. Something similar to this:
The problem with this solution is that when I modify the new element, the previousIndex element changes as well. I believe this is because they are reference-type, not value-type. How can I just copy (clone?) the information from one element to another without affecting each other any further?
Liutauras MedziunasPosted Feb 6, 2011, 12:49 PM
class Program
{
public static void Main()
{
int previousIndex = 1;
List
cantileverResults.Add(new CalculationResult(20));
cantileverResults.Add(new CalculationResult(30));
cantileverResults.Add(new CalculationResult(40));
cantileverResults.Add((CalculationResult)cantileverResults[previousIndex].Clone());
Console.WriteLine("Before change");
ShowResult(cantileverResults);
cantileverResults[3].Amount = 100;
Console.WriteLine("After change");
ShowResult(cantileverResults);
Console.ReadKey();
}
private static void ShowResult(List
{
foreach (var result in cantileverResults)
{
Console.WriteLine(result);
}
}
}
public class CalculationResult : ICloneable
{
private decimal amount = 0;
public decimal Amount
{
get { return this.amount; }
set { this.amount = value; }
}
public CalculationResult(decimal amount)
{
this.amount = amount;
}
public object Clone()
{
return this.MemberwiseClone(); // call clone method
}
public override string ToString()
{
return String.Format("Amount: {0}", this.amount);
}
}
If it was helpful please rate it.
Liutauras MedziunasPosted Feb 7, 2011, 11:26 AM
Thank you.
Suthish NairPosted Feb 7, 2011, 5:40 AM
Good sample..
JavierPosted Feb 6, 2011, 12:17 PM
Liutauras MedziunasPosted Feb 6, 2011, 11:15 AM
class Program
{
public static void Main()
{
int previousIndex = 1;
List
cantileverResults.Add(new CalculationResult(20));
cantileverResults.Add(new CalculationResult(30));
cantileverResults.Add(new CalculationResult(40));
cantileverResults.Add(cantileverResults[previousIndex].Clone());
foreach (var result in cantileverResults)
{
Console.WriteLine(result);
}
Console.ReadKey();
}
}
public class CalculationResult : ICloneable
{
private decimal amount = 0;
public CalculationResult(decimal amount)
{
this.amount = amount;
}
public object Clone()
{
return this.MemberwiseClone(); // call clone method
}
public override string ToString()
{
return String.Format("Amount: {0}", this.amount);
}
}
Please rate my post if it was helpful.