Joseph U. Joseph U. - 3 months ago 19
C# Question

Question about List scope in C#

I have a private function Load which creates a list, creates several objects and then binds a datagrid to the list. The code is similar to:

List<Car> cars = new List<Car>();
cars.Add(new Car("Ford", "Mustang", 1967));
cars.Add(new Car("Shelby AC", "Cobra", 1965));
cars.Add(new Car("Chevrolet", "Corvette Sting Ray", 1965));
_dgCars.DataSource = cars;


Now I would like to loop through the values in another private function. I tried something similar to:

foreach (Car car in cars) // Loop through List with foreach
{
// Need to access individual object properties here
}


I am getting an error that cars does not exist in the current context. Is there a change I can make that will allow the List to be available globally? Perhaps I can define it elsewhere?

Answer

Well, this is nothing to do with lists as such. It's general variable scope. You haven't shown where you've declared the cars variable or where you're trying to use it - but my guess is that you've made it a local variable, and the two snippets of code are in different methods.

You possibly want to make it an instance variable. For example:

public class Test
{
    private List<Car> cars;

    public void PopulateDataSource()
    {
        cars = new List<Car>
        {
            new Car("Ford", "Mustang", 1967),
            new Car("Shelby AC", "Cobra", 1965),
            new Car("Chevrolet", "Corvette Sting Ray", 1965)
        };
        _dgCars.DataSource = cars;
    }

    public void IterateThroughCars()
    {
        foreach (Car car in cars) // Loop through List with foreach
        {
            ...
        }
    }
}