-1

So, I have a simple C# application. The application lets a user enter a test score, and click Add button. When clicked, the text box contents (if valid) should enter into the list object.

My current code is saying that it the object doesn't exist in the current context.

private void ScoreCalculatorApplication_Load(object sender, EventArgs e)
    {
        List<int> scoreList = new List<int>();
    }

    private void btn_Add_Click(object sender, EventArgs e)
    {
        scoreList.Add();//this line has the problem
    }

So, I am not sure why the scoreList doesnt exist, because the ScoreCalculatorApplication_Load method executes on loading the app.

Anyway, I also considered something like this:

private void ScoreCalculatorApplication_Load(object sender, EventArgs e)
        {
             //remove this method.
        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
           //is there a test to see if this object exists?
            if (//see if the list does not exist)
                //if not existant, create it here.
            scoreList.Add();
        }

So, The problem is I dont know how to test if the object exists.

user3175451
  • 163
  • 1
  • 14

2 Answers2

3

The problem here is that you're creating scoreList in a more restrictive scope than btn_Add_Click exists in. You've defined it within the scope of the ScoreCalculatorApplication_Load method, which means that reference will be automatically garbage collected after the method completes, and will never be accessible outside that method.

If you want the scoreList object to be accessible to all methods within your class, you need to make a field or property. Within the class scope, create and initialize a List:

private List<int> scoreList = new List<int>();
private void ScoreCalculatorApplication_Load(object sender, EventArgs e)
{
    /// put whatever else you need to do on loading here
}

scoreList will now be accessible within any given instance of your class. Note that if you need scoreList to be accessible by other objects, you should make it a public property, rather than a private field.

Note that there's not really a need to check whether an object "exists" in the sense you seem to mean -- the program will not compile and run if you've referenced an object or method that does not exist in that scope. If you like, you can check if the scoreList has been initialized and can be populated by checking if it is null, e.g. if (scoreList == null).

furkle
  • 5,019
  • 1
  • 15
  • 24
1

furkle answers the main issue.

Just wanted to answer your supplmentary question that now scoreList is in scope you can test if it has been initialised with if(scoreList==null)

Stewart_R
  • 13,764
  • 11
  • 60
  • 106