Is it possible to clone an object, when it's known to be a boxed ValueType, without writing type specific clone code?
Some code for reference
List<ValueType> values = new List<ValueType> {3, DateTime.Now, 23.4M};
DuplicateLastItem(values);
The partical issue I have is with a value stack based virtual instruction machine. (And Im too lazy to write typeof(int) typeof(DateTime)....)
update I think I confused myself (and a few other people). The working solution I have is;
List<ValueType> values = new List<ValueType> { 3, DateTime.Now, 23.4M };
// Clone
values.Add(values[values.Count() - 1]);
// Overwrite original
values[2] = 'p';
foreach (ValueType val in values)
Console.WriteLine(val.ToString());
In general, when we try to copy one object to another object, both the objects will share the same memory address. Normally, we use assignment operator, = , to copy the reference, not the object except when there is value type field. This operator will always copy the reference, not the actual object.
The '=' operator then copies the reference rather than the object (and it works fine for a Value Type). The MemberwiseClone() function in the superclass System is used by default to achieve this behavior. This is referred to as "Shallow Copy". We use the Clone() method from the System.
You can use a hack using Convert.ChangeType
:
object x = 1;
var type = x.GetType();
var clone = Convert.ChangeType(x, type);
// Make sure it works
Assert.AreNotSame(x, clone);
The result is copy of the value boxed in new object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With