Home > Net >  How can I replace "this" when referencing to it somewhere else?
How can I replace "this" when referencing to it somewhere else?

Time:10-04

I'm trying to solve a problem me and some other students had (Windows Forms; the teacher told us to just work around it). In the constructor we could write this.select(), this.text etc... form1.select() wouldn't work nor would anything else we could think of (not much). When looking at the "Form" definition I found a method that was protected.

 public Form1()
        {
            InitializeComponent();
            this.Text = "Lorem";
            Form1.select();
        }

public selectForm(){
            Form1.Select(); //throws Error
}

CodePudding user response:

The name you need to use changes depending on where the current code is executing. Consider the following example (which isn't WinForms but a Console application, but the code looks the same and will behave just the same regarding variable names):

public class Form1
{       
    internal void Select(){
        Console.WriteLine("Selected!");
    }
    
    internal void JustAnExample()
    {
        this.Select();
    }
}

class Program
{
    static void Main(string[] args)
    {            
        var form1 = new Form1();
        form1.Select();
        form1.JustAnExample();
        SomeMethod(form1);
    }

    static void SomeMethod(Form1 x)
    {
        x.Select();
    }
}

Depending on where the program is currently executing, the Select-method needs to be called with either form1.Select(), because that's the name of that Form inside the Main() method. It needs to be x.Select(), because the name changes with the name of the argument.

If the code of execution is already within the class Form1 (like JustAnExample(), it's this.Select().

Note that there is only 1 Form1 being created, yet it has 3 different variable names. It could be even more.

  • Related