Search code examples
c#reflectionclrvalue-type

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());

Solution

  • I don't know, if I have totally misunderstood the question.
    Are you trying to do this?

    public static void Main()
    {
        List<ValueType> values = new List<ValueType> {3, DateTime.Now, 23.4M};
        DuplicateLastItem(values);
    
        Console.WriteLine(values[2]);
        Console.WriteLine(values[3]);
        values[3] = 20;
        Console.WriteLine(values[2]);
        Console.WriteLine(values[3]);
    }
    
    static void DuplicateLastItem(List<ValueType> values2)
    {
        values2.Add(values2[values2.Count - 1]);
    }