Search code examples
c#staticmethodsinstancenon-static

Is there any way for a static method to access all of the non-static instances of a class?


This is probably a dumb question but I'm going to ask it anyways... I am programing in C#.NET. I have a class that contains a non-static, instance EventHandler. Is it possible to trigger that EventHandler for every instance of the class that exists from a static method?? I know this is a long shot!


Solution

  • You can do this, but you'll need to create a static collection of all your objects:

    public class Thing
    {
       public static List<Thing> _things = new List<Thing>();
    
       public Thing()
       {
           _things.Add(this);
       }
    
       public static void SomeEventHandler(object value, EventHandler e)
       {
          foreach (Thing thing in _things)
          {
               // do something.
          }
       }
    }
    

    You'll want to watch out for accumulating too may "Things" . Make sure you remove them from the list when you don't need them anymore.