Referencing a public variable

Hi All,

Just a simple question;

I create a public list in classA lets say ListX and then I declare ListY in classB.
Initialize as;
ListY = ListX;

I make changes on ListY (remove, change some indexes etc.)

ListX also changes in the same way but I don’t want ListX to be updated from outside of classA (like a readonly). I can transfer the values of ListX to ListY with a simple loop but I think there could be an easier way to do that. I’m a bit confused with the keywords static, const, ref, readonly etc. Can anyone help me on that? Thanks.

If you want ListY to contain all elements of ListX, but not be a reference to it, not changing ListX when ListY changes, then you can create the list using the List(IEnumerable) constructor of a list:

List<MyType> ListY = new List<MyType>( ListX );

However the objects on the List still reference the same objects. So if you change object on list B, it also changes on list A. It’s a new list which is not a shallow clone, but the objects are the same. i.e objects added to list A will not appear to list B, but the changes made to objects on list A get applied to the same objects on list B.

You would need to implement a clone functionality to your objects or create new objects that have same values.