Get the reference of a specific class object in memory

Is there a way to retrieve a reference to the instance of a specific class?

I know the name of the class and I know that there is only one instance of it in memory.

I need to do that in order to call a method of that instance, but for design reasons I can not define that method as 'static'.

For example I would like to do something like:

public static void Main()
  ...
  object temp= GetCurrentInstanceOf("ClassToUse");
  temp.MethodINeed();
  ...
}
Jon Skeet
people
quotationmark

No, there's no way of doing that.

You could have a static variable in the class, to keep a reference to the "most recently created instance" available - this will prevent garbage collection, of course. Or you could make the class a singleton - a similar solution, but only allowing a single instance to ever be created.

But ideally, you'd just change the design to make the right instance available to you in different ways. Dependency injection is usually the way forward here, but without more details it's impossible to say exactly how it would pan out in your situation.

Anything relying on "global state" like this becomes a pain for testability. I strongly urge you to reconsider the overall design and data flow rather than using statics for global state.

people

See more on this question at Stackoverflow