Venna Michiki
Venna Michiki

Reputation: 33

foreach statement cannot operate on variables

I have to classes , Custom Car Factory Class and Custom Car Factory, I am trying to unregister the Custom Car from the custom car factory by using foreach to get all the data in the factory however I am getting an error of "foreach statement cannot operate on varialbles CustomCarFactory Because Custom CarFactory does not contain a public definition for 'GetEnumerator' "

Custom Car Factory class

[CustomCarFactory.cs]

internal class CustomCarFactory : ICarFactory
public CustomCarFactory(string make, string model, string serial, string plate)
    {
Make = make; 
Model = model;
Serial = serial;
Plate = plate;
}

internal string Make; 
internal string Model; 
internal string Serial; 
internal string Plate; 

Car Library Implementation class
[CarLibraryImplementation.cs]



internal static List<ICarFactory> CarFactories= new List<ICarFactory>(); 

In this part I register it to the custom factory

private static CustomCarFactory factory = new CustomCarFactory(string.Empty, string.Empty, string.Empty, string.Empty);
 private static void registerCarImplementation(string make, string model, string serial, string plate)
        {
            factory = new CustomCarFactory(make, model, serial, plate);

                CarFactories.Add(factory);

Then In this part, I will unregister it from the custom factory, but I am getting "foreach statement cannot operate on varialbles CustomCarFactory Because Custom CarFactory does not contain a public definition for 'GetEnumerator' "

   private static void UnregisterCarImplementation(string make, string model, string serial, string plate)
                {
        foreach (var item in factory)
    {
// Get make from current factory
// Get model from current factory

    }

}

Upvotes: 0

Views: 113

Answers (1)

Grant Winney
Grant Winney

Reputation: 66439

You're trying to iterate over a single item instead of a collection, which is why you're getting that error.

You could iterate over the CarFactories collection instead:

private static void UnregisterCarImplementation(
    string make, string model, string serial, string plate)
{
    foreach (var item in CarFactories)
    {
        if (item.Make == make && item.Model == model
            && item.Serial == serial && item.Plate == plate)
        {
            // take some action
        }
    }
}

Or you could use the RemoveAll method available to collections:

private static void UnregisterCarImplementation(
    string make, string model, string serial, string plate)
{
    CarFactories.RemoveAll(x => x.Make == make && x.Model == model
                                && x.Serial == serial && x.Plate == plate);
}

Upvotes: 1

Related Questions