-1

I have the following code:

public class Entity
{
    public int Number;
    public string Text;
}

System.Collections.Generic.List<Entity> list = new List<Entity>();
list.Add(new Entity() { Number = 100, Text = "hello1" });
list.Add(new Entity() { Number = 200, Text = "hello2" });

Entity sampleEntity = new Entity() { Number = 300, Text = "World" };

list[0] = sampleEntity // this does only replace the pointer in the list

list[0].Text = sampleEntity.Text; // this writes to the pointer in list
list[0].Number = sampleEntity.Number; // this writes to the pointer in list

What I would like to know if there is any possible way of performing a memcopy of the whole object data to the heap-location the list[0] entry points to? I mean in c++ it is a simple dereference *list[0] = *entity;

trincot
  • 317,000
  • 35
  • 244
  • 286

1 Answers1

0

Not unless Entity implements ICloneable (see Creating a copy of an object in C#).

I would personally just instantiate a new Entity.

list[0] = new Entity { Number = sampleEntity.Number, Text = sampleEntity.Text };

Omar Himada
  • 2,540
  • 1
  • 14
  • 31