Replace an existing object with a new one in the same place in memory

32 Views Asked by At

In C# it is possible to pool existing objects in an ObjectPool. But this only works for reference types that provide a method to reset the object to some well defined initial state. For example a type may implement IResettable interface or provide a method that mirrors its constructor.

I wonder if it would be possible to pool any arbitrary reference type. The steps would be the following:

  • Call ObjectPool<T>.Get() to get an instance.
  • Replace the memory pointed to by the recovered instance with a new fresh instance.
  • Use the new object and return it to the pool when done.

The question is if it is at all possible to achieve point 2. Theoretically it should be possible. I am, however, not sure if it is possible in C#. From what I understand the new keyword will always create an instance at an unoccupied "slot" in the managed heap. What would be needed for this to work is a way to create a new object at a specified memory location. Furthermore, one would need to make sure that the old object was disposed of, hoping that disposal is enough and call to the finalizer is not needed.

1

There are 1 best solutions below

4
Anders On

Only way to achieve that is to let the user of the pool get a PoolElement<T> instead of a instance of T. And make sure he access the instance through the PoolElement. Which you cant guarantee.

I wouldn't recommend this approach.

There are better ways, pub/sub for example.