Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to clone a ValueType?

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());
like image 638
Dead account Avatar asked Nov 26 '09 14:11

Dead account


People also ask

How to copy values of one object to another in C#?

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.

How to shallow copy an object in C#?

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.


1 Answers

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.

like image 140
Elisha Avatar answered Nov 16 '22 02:11

Elisha