Pregunta

I have a really complex object (many different properties and also objects which contain same class objects in them and also backwards reference to parent objects) as global in a static class, which is initialized by a static constructor for 1 time and I want it to stay so and never change after that. This object is used many many times in my code in different places, whereas sometimes a clone is made out of it, with care never to change anything in its original reference (and properties, subproperties, etc). However, I guess I made a mistake somewhere and I removed some of its subproperties. I can find where the mistake is by step by step debugging, but it will cost me much time. Is there a way to lock the whole thing (not just the reference, but the whole object with all its properties, no matter how deep they are) not to be altered again after it is initialized for the first time?

I tried looking at readonly modifier, but I guess it won't suit me because it constraints only the reference of the object and not everything that comes under it.

Also private won't suit me for the same reason.

Is there a better way to this?

¿Fue útil?

Solución

Is there a way to lock the whole thing

There is no way to prevent mutation of an object (or object graph) that is mutable. Put differently: If the object can be modified (such as if it has a public field that isn't readonly or if it has a property that has a setter), there is no way to prevent it from being modified.

I tried looking at readonly modifier, but I guess it won't suit me because it constraints only the reference of the object and not everything that comes under it.

Correct. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class. (Source: msdn)


However, you can design the type so it is immutable or at least so it can't be modified through public fields, properties or methods.

You might also consider to return clones of the object graph instead of the original object graph. If the clone gets modified, the original object graph is still unmodified.

Otros consejos

Sounds like you want a singleton?

build a function in the class that contains this object:

function getComplexObject()

  // is m_object NULL? 

    // instantiate object. 

  // return m_object. 

And make m_object the property of the class.

Then always use this function to get the object. This way you can be sure it'll only be created once.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top