-1

I have a static list that contains objects of a class.

List<Hooking>

The object Hooking has an instance property named HookingAreaRadius. When I change the HookingAreaRadius by the following code

List[i].HookingAreaRadius = 0.5

every HookingAreaRadius of every object in the list is set to 0.5. Firstly, why is that? And secondly, how can the property of the object (accessed via the static list) be set individually?

Side note: The Hooking object has many instance properties, so I cannot simply instantiate a new object.

I tried this:

        public Hooking SetHookingAreaRadius(double hookingAreaRadius)
        {
            var cloned = (Hooking)MemberwiseClone();
            cloned.HookingAreaRadius = hookingAreaRadius;
            return cloned;
        }

But this resulted in bizarre side effects.

Any help is appreciated!

Thomas
  • 1
  • 1
  • 1
    I think you got the gist of the error. It seems that you should create a deep copy of each Hook object when adding to your list. Here's another question regarding deep copy that could help you out: https://stackoverflow.com/questions/78536/deep-cloning-objects – Emanuel Hiroshi Aug 31 '23 at 14:34
  • *"bizarre side effects"* - such as? This is a very vague description of what the problem is with the code shown – UnholySheep Aug 31 '23 at 14:35
  • 1
    It sounds to me like you may have a problem in either the object itself (e.g. the properties are static) or in whatever code fills up that list of objects -- if updating one is updating all of them, then presumably you don't actually have multiple objects but rather multiple references to the same object. – Jacob Mattison Aug 31 '23 at 14:35
  • The name of this class makes me suspect that the value of this property is hooking an object. – shingo Aug 31 '23 at 14:50
  • 2
    Show the Hooking class and how you add multiple (or think multiple) to the List. – Ralf Aug 31 '23 at 15:14
  • 1
    Fundamentally we need a [mcve] here. – Jon Skeet Aug 31 '23 at 15:26

0 Answers0