Question

I am accesing another file by doing this:

 public void startUpdateChecking()
    {
        UpdateHandler process = new UpdateHandler();
        process.initialize(this);
    }

The same class that 'startUpdateChecking' function is in I have this example functon aswell:

 public void changeText(string Text)
        {
          label2.Text = Text;
        }

Now in the UpdateHandler class I am doing this:

 public Form form;
        public void initialize(Form test)
        {
            Thread update = new Thread(checkForUpdates);
            update.Start();
            form = test;
            edit();
        }

        public void edit() {
        form.changeText("test");
        }

But 'form' has no clue what changeText is for some reason, how would I make it so I can use functions from another class (Form2 class) WITHOUT the need for static function?

I tried doing:

Form2 form = new Form2();

And I could control and acces things from Form2, but this makes a new form instead of controlling the current one that is active (aka nothing visible happends using this).

Thanks in advance.

Was it helpful?

Solution

One way would be to use a delegate to pass the changeText method instead of passing the whole form. This should help separate the classes and I think would improve the design.

A quick way of doing this would use an action. Instead of passing in Form to initialize pass Action<Text>

The form side code would change to

 public void startUpdateChecking()
    {
        UpdateHandler process = new UpdateHandler();
        process.initialize((s) => {changeText(s);});
    }

and the UpdateHandler side code would change to

    public void initialize(Action<string> outputMethod)
    {
        Thread update = new Thread(checkForUpdates);
        update.Start();
        output= outputMethod;
        edit();
    }

    public void edit() {
    output("test");
    }

OTHER TIPS

Try to return a value from initialize and then pass that on to ChangeText.

like this:

public void startUpdateChecking()
{
    UpdateHandler process = new UpdateHandler();
    string Value1 = process.initialize(this);
    ChangeText(Value1);
}

Initialize should then be a string, im not sure what the form is doing there, and what it has to do with the Thread update, thats something you probably know more about

    public string initialize(string test)
    {
        Thread update = new Thread(checkForUpdates);
        update.Start();
        form = test;
        return test;
    }

Just don't try to call a function from out a class, best way is to return from a class and then call a function

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top