Search code examples
c#.netstaticinstance

C# calling public fields from a public static class


I'm just learning C# after using VBA for many years, I'm not a professional and this is something I do in my leisure. I'm looking to replicate the logic of using a public variable that can be accessed from a method and incremented by one each time when clicking button cmdPublicVartest , Below is the code I have so far, but am getting the error An object reference is required for the non-static field, method, or property, in the publicvar class, it looks because it's a static class, however if I remove it from a static class, I would have to call an instance of the class on the button cmdPublicVartest. Is there a way I can keep publicvar a static class, so I don't have to do an instance of the class on the button?

namespace testDB
{
    public partial class Database : Form
    {
        public string publictest = "public test";
        public int pUblicint = 0;


         public static void   PublicVar()
        {
             
            MessageBox.Show(publictest + pUblicint);
            pUblicint++;

        }
        private void cmdPublicVartest_Click(object sender, EventArgs e)
        {
            testDB.Database.PublicVar();
        }
    }
}

Solution

  • You cannot access non-static fields from a static method because they belong to an instance of the class, and when calling a static method you do not have an instance.

    You could either make the fields static like this

    public partial class Database : Form
        {
            public static string publictest = "public test";
            public static int pUblicint = 0;
    
    
            public static void PublicVar()
            {
    
                MessageBox.Show(publictest + pUblicint);
                pUblicint++;
    
            }
            private void cmdPublicVartest_Click(object sender, EventArgs e)
            {
                testDB.Database.PublicVar();
            }
        }
    

    Or make the method non-static like this

    public partial class Database : Form
        {
            public string publictest = "public test";
            public int pUblicint = 0;
    
    
            public void PublicVar()
            {
    
                MessageBox.Show(publictest + pUblicint);
                pUblicint++;
    
            }
            private void cmdPublicVartest_Click(object sender, EventArgs e)
            {
                PublicVar();
            }
        }