0

I have a question if it is possible to change field value of the base class, from derived class. In my case, i have two classes base class with windows form RichTextBox, and I want use derived class to clear RichTextBox.

Initialize RichTextBox:

        this.rtfCode.Location = new System.Drawing.Point(45, 26);
        this.rtfCode.Name = "rtfCode";
        this.rtfCode.ShowSelectionMargin = true;
        this.rtfCode.Size = new System.Drawing.Size(100, 96);
        this.rtfCode.TabIndex = 1;
        this.rtfCode.Text = "some text";

Base class:

    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Console.WriteLine(this.rtfCode.Text);
        DerivedClass f = new DerivedClass();
        Console.WriteLine(f.rtfCode.Text);
    }
}

My Derived class

    class DerivedClass:Program
{
    public DerivedClass()
    {
        base.rtfCode.Clear();
    }
}

when i execute program and press the button in RichTextBox i still see text.

ProgShiled
  • 154
  • 1
  • 1
  • 12

1 Answers1

1
Program a = new Program(); // a is an instance of Program
Console.WriteLine(a.rtfCode.Text);
DerivedClass f = new DerivedClass();// f is an instance of DerivedClass, which has nothing to do with a
Console.WriteLine(a.rtfCode.Text);

a and f are not the same instance. The fact that DerivedClass... derives from Program doesn't change anything to this.

You have to replace the last line by

Console.WriteLine(f.rtfCode.Text);
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122