views:

47

answers:

1

Ive been playing around with delegates trying to learn and I ran into one small problem Im hoping you can help me with.

class myClass
{
   OtherClass otherClass = new OtherClass(); // Needs Parameter
   otherClass.SendSomeText(myString);
}

class OtherClass
{
   public delegate void TextToBox(string s);

   TextToBox textToBox;

   public OtherClass(TextToBox ttb)  // ***Problem***
   {
       textToBox = ttb;
   }

   public void SendSomeText(string foo)
   {
       textToBox(foo);
   }
}

the form:

public partial class MainForm : Form
   {
   OtherClass otherClass;

   public MainForm()
   {
       InitializeComponent();
       otherClass = new OtherClass(this.TextToBox);
   }

   public void TextToBox(string aString)
   {
       listBox1.Items.Add(aString);
   }

}

Obviously this doesnt compile because the OtherClass constructor is looking for TextToBox as a parameter. How would you recommend getting around the issue so I can get an object from myClass into the textbox in the form?

+2  A: 

You can change the OtherClass to something like

class OtherClass 
{ 
    public delegate void TextToBox(string s); 

    TextToBox textToBox; 

    public OtherClass() 
    { 
    } 
    public OtherClass(TextToBox ttb)  // ***Problem***  
    { 
        textToBox = ttb; 
    } 

    public void SendSomeText(string foo) 
    { 
        if (textToBox != null) 
            textToBox(foo); 
    } 
} 

But I am not quite sure what you wish to achive with

class myClass 
{ 
   OtherClass otherClass = new OtherClass(); // Needs Parameter 
   otherClass.SendSomeText(myString); 
}
astander
I really dont have much control over myClass. Its a stream Im receiving via API. Not sure why I didnt think of adding another constructor.
Leroy Jenkins