Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 777
PICyourBrain Avatar asked Mar 01 '10 15:03

PICyourBrain


People also ask

How do you access non-static members within a static method?

The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs.

Can static methods access other static methods?

Static methods are class methods, and non-static methods are methods that belong to an instance of the class. Static methods can access other static methods and variables without having to create an instance of the class.

Why can't static methods access non-static fields?

Non-static variables are part of the objects themselves. To use a non-static variable, you need to specify which instance of the class the variable belongs to. ... In other words, non-static data cannot be used in static methods because there is no well-defined variable to operate on.

How can static method be used in non-static object?

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.


1 Answers

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.

like image 66
David Morton Avatar answered Oct 19 '22 22:10

David Morton