简体   繁体   中英

Does Array.sort changes references in C#?

In my C# code, I have a array of objects. And many of these objects are referenced in another class. If Array.sort method is used to somehow sort this array of objects, then will it affect those references? Is it same for the arrays and lists?

No it won't affect anything. The important thing to realise is that you don't actually have an array of objects. You have an array of references . So if you have objects A and B, then the array may contain references to A and B. When you sort the array, those references may change order - but the objects themselves don't get changed. Anything else which had a reference to the objects won't see any change just because you're shuffling the references.

To put it another way: suppose you have a shopping list of items you want to get. You can sort the shopping list to put it in some efficient order for shopping. That doesn't change where the items are, and it doesn't change anyone else's shopping list.

No, it will not affect references in other classes. Same for lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM