-3

Anybody can think of a way of finding the instance of a class inside the code so it's available to use? (Without having it's reference for start)

class FindMeClass
{
    internal FindMeClass()
    {
        Console.WriteLine("FindMeClass()");
    }

    ~FindMeClass()
    {
        Console.WriteLine("~FindMeClass()");
    }
}

static void FindMe()
{
    new FindMeClass();
    // Find the class here
    GC.Collect();
    GC.WaitForPendingFinalizers();
}
Alexandru Lache
  • 477
  • 2
  • 14
  • What are the rules of the game? Would registering it with an IoC container be OK? – H H Aug 04 '14 at 07:36
  • -1 for the total anti pattern use of GC. – H H Aug 04 '14 at 07:36
  • 5
    I assume you mean the *instance*, rather than the class itself? – Jon Skeet Aug 04 '14 at 07:38
  • 1
    The question isn't even clear... surely you are looking for an object and not for a class? – Emond Aug 04 '14 at 07:38
  • Yes, I mean the instance, you can use it's Type/Name – Alexandru Lache Aug 04 '14 at 07:44
  • 2
    Whole point that you don't have a reference to an object is that you can no longer reference it. **Why** do you want to do this? – Lasse V. Karlsen Aug 04 '14 at 07:46
  • The point of finding the class is so that the Garbage Collector doesn't destroy it, the use of Garbage Collector is to show that the class was found, for easy testing, it's just an exercise to test if it's possible, no real project attached – Alexandru Lache Aug 04 '14 at 07:48
  • If there are no references to it, it could have already been destroyed at the time you try to find it. – Matthew Watson Aug 04 '14 at 07:50
  • You can resurrect it from its finalizer. Look for object resurrection in C# through google. – Lasse V. Karlsen Aug 04 '14 at 07:52
  • Just focus on the solution, I tested it and it's not destroyed, if you step through code the destructor gets called either when GC is forced, when program terminates or when GC is invoked because of another reason (low memory) – Alexandru Lache Aug 04 '14 at 07:52
  • 1
    There is no solution, unless you have some code somewhere that has access to the object (either in the class itself or via a reference). – Matthew Watson Aug 04 '14 at 07:54

1 Answers1

0

In the destructor of the object you could put a reference to it in a global static object.

That way you resurrect the object and it becomes reachable again and will not be garbage collected.

Don't forget to re-register the object for garbage collection. See: Usages of object resurrection

In general: this is a waste of effort, just keep a reference to the objects you don't want to be deleted.

Community
  • 1
  • 1
Emond
  • 50,210
  • 11
  • 84
  • 115