views:

100

answers:

2

I am writing a class library(API) in C#. The class is non-static and contains several public events. Is it possible to trigger those events from a static method in a separate class? For example...

class nonStaticDLLCLASS
{
   public event Event1;

   public CallStaticMethod()
  {
     StaticTestClass.GoStaticMethod();
  }
}

class StaticTestClass
{
   public static GoStaticMethod()
   {
     // Here I want to fire Event1 in the nonStaticDLLCLASS
     // I know the following line is not correct but can I do something like that?

     (nonStaticDLLCLASS)StaticTestClass.ObjectThatCalledMe.Event1();

   }
}

I know you typically have to create an instance of the non-static class in order to access it's methods but in this case an instance has already been created, just not by the class that is trying to access it.

+4  A: 

No, instance members can only be invoked/accessed on a valid instance of the type.

In order for this to work you must pass an instance of nonStaticDLLCLASS to StaticTestClass.GoStaticMethod and use that instance reference to invoke/access the non-static members.

In your example above how do you specify which instance of the type you are accessing? The static method has no knowdlege of any instance so how does it know which one to use or if there are any loaded in memory at all?

Consider this example:

using System;

class Dog
{
    public String Name { get; set; }
}

class Example
{
    static void Main()
    {
        Dog rex = new Dog { Name="Rex" };
        Dog fluffy = new Dog { Name="Fluffy" };
    }
    static void sayHiToDog()
    {
        // In this static method how can I specify which dog instance
        // I mean to access without a valid instance?  It is impossible since
        // the static method knows nothing about the instances that have been
        // created in the static method above.
    }
    static void sayHiToDog(Dog dog)
    {
        // Now this method would work since I now have an instance of the 
        // Dog type that I can say hi to.
        Console.WriteLine("Hello, " + dog.Name);
    }
}
Andrew Hare
+2  A: 

Instance methods can only be called on instances. In your example, the instance is calling the static method. Can you give the static method a parameter allowing the instance to pass in a reference to itself? Something like this:

class nonStaticDLLCLASS
{
   public event Event1;

   public CallStaticMethod()
  {
     StaticTestClass.GoStaticMethod(this);
  }
}

class StaticTestClass
{
   public static GoStaticMethod(nonStaticDLLCLASS instance)
   {
     // Here I want to fire Event1 in the nonStaticDLLCLASS
     // I know the following line is not correct but can I do something like that?

     instance.Event1();

   }
}

I think you need to clarify your question to specify why you can't do something like this, or why the instance can't raise its own event.

Sean Devlin
That makes a ton of sense. I think my brain just wan't working properly!
Jordan S