'Call async inside public static bool

I wrote code about the settings page that uses static bool then I need to Check If the public static bool changed or not In the form that I needed to call (Form1 Is main form and Can be opened Once But Form2 Can open >1) then I wrote this code

Form1:

    private static bool Called = false;

    public static bool HideButton
    {
        get { return Called; }
        set
        {
            if (Called != value)
            {
                Called = value;
                Update(); //function about updating buttons
            }
        }
    }

Form2:

private void checkBox5_CheckedChanged(object sender, EventArgs e) { 
    if (checkBox5.Checked) 
    { 
        Form1.HideButton = true; 
    } 
    else 
    { 
        Form1.HideButton = false; 
    } 
}

Then it said that you can't run non-static inside static So I have an idea If I can check public static bool then call async void that is not static. any idea?



Solution 1:[1]

Well, static means not instance, so you have one and only one Called value for all Form1 instances. When you try to call Update() within static property set, the compiler complains: it doesn't know on which instance should it be called (imagine, that there are three opened Form1).

You can either add some logic, e.g. let call Update on all opened Form1:

using System.Linq;

...

private static bool Called = false;

public static bool HideButton
{
    get { return Called; }
    set
    {
        if (Called != value)
        {
            Called = value;

            // Assuming WinForms  
            // We call Update on all opened Form1 forms
            foreach (var form in Application.OpenForms.OfType<Form1>())
                form.Update(); 
        }
    }
}

Or you may let each Form1 instance have its own Called, i.e. drop static:

private bool Called = false;

public bool HideButton
{
    get { return Called; }
    set
    {
        if (Called != value)
        {
            Called = value;

            Update(); 
        }
    }
}

Please, note, that async is quite a different conseption which is orthogonal to static

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1