Is it possible? Would a get set work?
Sending an array as a parameter but not allowing the values in it to change in the receiving script?
Quick answer is just copy the array, which you can do with arrayName.Clone(), which you’ll have to cast to the array type I think, or you can use arrayName.ToArray() if you include System.Linq which implicitly casts to the array type in the process. Worth noting that this will keep the function from being able to change the structure of the original collection (the order of objects outside of the function), but if the collection is of a bunch of reference-type objects, you can’t stop changes to those objects themselves and they’ll be reflected in both collections just the same.
If you’re looking for some sort of built-in safety, then either use a read-only wrapper on the array you’re sending in by using Array.AsReadOnly(arrayName) or make your own collection type. It would be even faster to just not edit the array from within the function- is there really a need to enforce this?
Thank you for the answer. It makes sense that those references can not be read only I just wanted to know if there was a solution for it. I think I will go with the not editing part then since there is really no need to enforce it like you said, just that I would want it that way.
IMO, it’s normally bad form to modify the parameters of a function unless that’s the specific purpose of the function. It’s neater to have a return value instead.
The call will be made far too often to return it as a value from an event. This solution works fine I think.
He meant that, just as a general rule of thumb, never change parameters that are given to functions unless that’s explicitly seen as the whole purpose of the function. Instead, just create some sort of a return value and pass it back, if communicating back to the calling script is even necessary.
A function should do exactly what it’s supposed to do, and absolutely nothing else, so that you can just look at the method definition in IntelliSense, or read a one or two line description in the documentation, and understand everything you need to about it to use it properly. In that sense, it’s the responsibility of the method to make sure not to change things around unnecessarily, and not the responsibility of the caller to protect itself from the method.
Thank you for your great replies. I will just leave it be then.