Question

I have a situation when I need to access the private members of a class in an embedded private class. How can I do it efficiently.

public partial class Form1 : Form
{
    // this private label will be used only in this form
    private class MyFormLabel : Label
    {
        MyFormLabel() 
        {
            this.BorderStyle = BorderStyle.FixedSingle;
            // ?? how to pass the from label_Click (without delegates)?
            this.Click +=new EventHandler(????); 
        }
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void label_Click(object sender, EventArgs e)
    {
        // displays the form caption
        MessageBox.Show(this.Text);
    }
}   

NotaBene: I add dynamically the controls to the form, so I would be sure that after creation they are already subscribed to this event.

Was it helpful?

Solution

You can access private members of classes from nested classes. Of course, to access an instance method you still need an instance of the class.

OTHER TIPS

In this case, just do it the othwe way around, e.g. after InitializeComponent() do a myFormLabel.Click += label_Click

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top