tags:

views:

320

answers:

1

I'm trying to pass the name of a method from one class to another class, so the other class can "subscribe" her to an event that the first class is not aware of. Let's say I've got those classes:

class1
{
  public void method1(string msg)
  {
    //does something with msg
  }

  public void i_make_a_class2()
  {
    class2 bob = new class2(method1);
  }
}

class2
{
  delegate void deleg(string msg);
  deleg deleg1;

  public class2(string fct)
  {
    // What I'm trying to do would go there with "fct" converted to function signature
    deleg1 = new deleg(fct);
    // Rest of the class constructor...
  }
  private void method2()
  {
    deleg1(im_a_String);
  }
}
+1  A: 

You don't really want to pass the name of the function - you want to pass the delegate function itself - that's the key to delegates. Give me a minute and i'll write the code the way you want it.

Here you go:

public delegate void deleg(string msg);

public class class1
{
  public void method1(string msg)
  {
    //does something with msg
  }

  public void i_make_a_class2()
  {
    class2 bob = new class2(method1);
  }
}

public class class2
{
  deleg deleg1;
  string im_a_String = "Test";

  public class2(deleg fct)
  {
    deleg1 = fct;
    // Rest of the class constructor...
  }
  private void method2()
  {
    deleg1(im_a_String);
  }
}
Chris
Thanks!With Johannes's reply I've done something like this, but not as simple! I now feel like I'm able to barely scratch the surface of C#! That's a big plus! ;-)
Tipx
Delegates is more than just scratching the surface of c#, you should congratulate yourself if you can understand how it works as above.
Chris