Simillion
Simillion

Reputation: 1

I can't get a member inside a private class to be accessible from another private class

    {
    public partial class form1 : Form
    {
        public form1()
        {
            InitializeComponent();
        }
        public Button ButtonName { get { return } }
        public static int initFaggleCount;

        private void button1_Click(object sender, EventArgs e)
        {
            int faggleCount = initFaggleCount++;
            string finalCalc = faggleCount.ToString();
            label1.Text = finalCalc;
            /*
            Console.WriteLine(faggleCount);
            Console.ReadLine();*/
        }
        private void button2_Click(object sender, EventArgs e)
        {
            /*TextWriter tw = new StreamWriter("SavedFaggleCount.txt");
            tw.WriteLine();
            tw.Close();*/
            Console.WriteLine(faggleCount);
            Console.ReadLine();
        }
    }
}

I would like the integer faggleCount to be accessible from button2 so that I can successfully Console.WriteLine(fagleCount); from button2. I'm a noob and any help is appreciated. Thanks!

Upvotes: 0

Views: 60

Answers (2)

Sweeper
Sweeper

Reputation: 274835

In your code, faggleCount is local to the method i.e. only code in the method can access it. What you need to do is to move the variable to the class-level. like this:

public class form1 : Form {
    int faggleCount;
    //your other code here
}

As you can see, the variable is now in the class, not in the method. This way all the methods in the class can access it, and even a inner class can access it too!

This problem is very common among beginners. Understanding the scope of the variable is pretty hard. In short, A variable in a class can be accessed in the class, a variable in a method can be accessed in the method.

Upvotes: 0

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

instead of declaring local variable inside method body you can declare instance variable so that all members of class can access it.

public partial class form1 : Form
{
    int faggleCount; //declare instance variable.
    public form1()
    {
        InitializeComponent();
    }
    public Button ButtonName { get { return } }
    public static int initFaggleCount;

    private void button1_Click(object sender, EventArgs e)
    {
        faggleCount = initFaggleCount++; //use instance variable
        string finalCalc = faggleCount.ToString();
        label1.Text = finalCalc;
        /*
        Console.WriteLine(faggleCount);
        Console.ReadLine();*/
    }
    private void button2_Click(object sender, EventArgs e)
    {
        /*TextWriter tw = new StreamWriter("SavedFaggleCount.txt");
        tw.WriteLine();
        tw.Close();*/
        Console.WriteLine(faggleCount); //use instance variable
        Console.ReadLine();
    }
}

Upvotes: 1

Related Questions