Search code examples
c#classtextmethodscall

How do I call a method of an other class without creating a new object of the class? c#


I'm a beginner in c# and I'm working on a small windows forms application, a text editor which can control the text of my RichTextBox1. (change font type, font size, etc.) I want to create a Find and Replace Dialog to my project. It has a TextBox (txtText), which's text should be examined in RichTextBox1.Text, and a "Find" Button (btnFind) control. I have the code, which examines and selects the next text in RichTextBox1.Text which matches the text of txtText after the cursor's location:

public void FindNextText(string Text)
{
    int TextSelectionStartIndex;
    int CursorPosition = RichTextBox1.SelectionStart;
    if (RichTextBox1.SelectedText == Text)
    {
        TextSelectionStartIndex= RichTextBox1.Text.IndexOf(Text, CursorPosition + 1);
    }
    else
    {
        TextSelectionStartIndex= RichTextBox1.Text.IndexOf(Text, CursorPosition);
    }
    RichTextBox1.Select(TextSelectionStartIndex, Text.Length);
}

The only problem is, that this method is in my MainForm class, and the Find button, which's Click event calls this method is in my FindAndReplaceForm class.

I've tried this code to call it:

public partial class FindAndReplaceForm : Form
{
//...
    private void btnFind_Click(object sender, EventArgs e)
    {
        MainForm mf = new MainForm();
        mf.FindNextText(txtText.Text);
    }
//...
}

but if I do so, the new MainForm's method will be called and executed, and nothing will be selected in the original form's RichTextBox1.Text.

Can anyone help me how to call this method of the original MainForm without creating a new object of the class? Is it possible without setting MainForm to a parent, and FindAndReplaceForm to a child form?

Thanks for any kind of help!


Solution

  • In order to call an instance method like FindNextText you always need an instance of the class.

    However this doesn't mean you have to create the instance using new each time, that would defeat the purpose of object oriented programming. If your FindAndReplaceForm needs a reference to the MainForm, which in your cast it clearly does then just add a reference to it, e.g.

    public class FindAndReplaceForm {
        private readonly MainForm _mainForm;
    
        public FindAndReplaceForm(MainForm mainForm) {
             if (mainForm == null) throw new ArgumentNullException("mainForm");
    
            _mainForm = mainForm;
    
            InitializeComponent();
        }
    
        [...]
    }
    

    and when you create that form in one of your MainForm methods simply add this as a parameter: var findForm = new FindAndReplaceForm(this);.

    Then you can just call

    _mainForm.FindNextText(txtText.Text);
    

    Alternatively you can also use a property with a public setter in the FindAndReplaceForm but personally I prefer the user of constructor.