serhio
serhio

Reputation: 28586

access members in a private class

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.

Upvotes: 0

Views: 115

Answers (2)

Matthew Scharley
Matthew Scharley

Reputation: 132274

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.

Upvotes: 1

Lucero
Lucero

Reputation: 60190

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

Upvotes: 0

Related Questions