views:

131

answers:

2

Here is an example of what i would do in vb:

Public Class Class1
    Public Shared WithEvents Something As New EventClass

    Public Shared Sub DoStuff() Handles Something.Test

    End Sub
End Class

Public Class EventClass
    Public Event Test()
End Class

Now how do i do this in c#. I know there is not handles clause in c# so i need some function that is called and assign the event handlers there. However since its a shared class there is no constructor i must put it somewhere outside of a function.

Any ideas?

+2  A: 

You can use the static constructor...

static readonly EventClass _something;

static Class1()
{
  _something = new EventClass();
  _something.Test += DoStuff;
}

static void DoStuff()
{
}
Just remember that static constructors are not automatically called when program starts like in c/c++. They are called when the static class is accessed for the first time in you code same goes for all static member variables.
affan
@affan thanks for the info..
Srinivas Reddy Thatiparthy
+1  A: 

Try the following

public static class Class1 {
  private static EventClass something;
  public static EventClass Something {
    get { return something; }
  }
  static Class1 {
    something = new Class1();
    something.Test += DoStuff;
  }

  public static void DoStuff() {
    ...
  }
}
JaredPar