C# struct question

Im working on some scripting that requires me to duplicate a struct, to
have 2 copies of it.
But I seem to end up with 2 pointers to the same struct.

Off the top of my head the script is setup sort of like this

public struct myStruct {

public int m_count;
public string m_words;

public ArrayList = m_myList;

}

//-------------------------
Used in functions later on
.
.
public void myFunctionThingy ( myStruct oldStruct);
{

myStruct newStruct;

.
.
…

newStruct = oldStruct;

}

so what I want is “newStruct” to be a duplicate of oldStruct (ie same
values…especially the arrayList), but what I am getting is newStruct
and oldStruct seem to be pointers to the same object. So if I update one
it also updates the other.

I think it does only update both ArrayList members since I think these are only pointers. Now both struct objects hold the pointer to the same array.

Maybe you have the same problem with the string, I’m not sure how it’s handled in C# but in C++ strings (char*) are only pointers to an “array” of characters.

Anyone correct me if I’m wrong here.

If ArrayList is a class, then it’s just going to copy the reference.

To elaborate: structs are always copied by value instead of by reference, so new struct and old struct are in fact different instances. However, the copy is a so-called “shallow copy”, meaning that all the fields are copied directly. Since ArrayList is a class, as stated before, it will copy the reference to the array instance. You have two different structs pointing to the same array.

If you want the complete array to be copied, you’ll need to add a copy constructor to your struct, where you manually duplicate the array. Note that this is most likely not what you want to do. You seem to want two “instances” of the struct, which is impossible. Structs behave like base types like int and float. When you pass a struct to a function, that function will work with a copy.

Structs are (mostly) useful for creating small units of data that need to be placed in large arrays that require fast access (because they are used in performance critical pieces of code). The most common example being mathematical entities like the Unity Vector3 struct.

I think your struct should be a class.

Thanks this fixed it.
That and a manual copy of list members

foreach (i in list1)
list2.add(i)

-LW