Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing specific form using a method in C#

Tags:

methods

c#

forms

Hi I have some forms in my project and I want to do a method that closed one of them. The method is:

public static void close_form (Form frm)
{
    frm.Close();
}

And I use it this way:

public partial class myForm : Form
{
   close_form(myForm);
}

but when I want to run the application I get error: myForm is a 'type' but is used like a 'variable'

What am I doing wrong? Is there another way to close the form without using this.close()?

like image 980
user2254436 Avatar asked Feb 17 '23 21:02

user2254436


1 Answers

You are passing type of the form i.e. myForm you need to pass object of type, you can pass this

public partial class myForm : Form
{
   close_form(this);
}

Here myForm is new type that inherits from Form type and is not instance of your current form. The keyword this represents the current instance of class you can pass that to close_form you can read more about this here.

There is no reason for closing form by calling a function if function just have only one statement to close the form unless you are doing this for learning or you could have some reason for closing forms through function like logging some information like closing form name and time etc. You simple call this.Close instead of calling close_form and passing current form to it.

like image 136
Adil Avatar answered Feb 19 '23 09:02

Adil