Search code examples
c#classpublic-method

Use class method from another class


I am trying to use a method inside class, from another class.

namespace Crystal.Utilities
{
   public class Logging
   {
      public static void Log()
      {
          //dostuff
          Crystal.MainForm.general_log_add_item("Hello World");
      }
   }
}

namespace Crystal
{
   public partial class MainForm : Form
   { 
      public void general_log_add_item(string msg)
      {
         listBox1.Items.Add(msg);
      }
   }
} 

I want to be able to call Crystal.Utilities.Logging.Log() from anywhere, and that to be able to call Crystal.MainForm.general_log_add_item() . But It doesn't let me, because if I put it as public, then I can't see it, if it's static then It can't interact with my listbox.


Solution

  • You have to understand that the window is not static, there is one instance of him, thats why the method cant be static, you can use Application.Windows to reach this instance and call the add method.

    or you can register the window in his constructor on another class that will mediate the Logging and the window.

    If you don't understand tell me and I'll try to be more clear