Hi guys,

I'm getting a simple error and I need your help. I want to display every object in a list by returning that object as a string but I'm getting the following error:

The name 'myBikeList' does not exist in the current context

My code:

List<Vehicle> myList;//= new List<Vehicle>();
        //METHOD
        public override string ToString()
        {
            foreach (Motorbike bike in myList)
            {
                string myBikeList = ("[MOTORBIKE]: " + bike.VehicleRegistration + " " + bike.EngineSize
                                + " " + bike.Make + " " + bike.Model + " " + bike.EngineSize + " "
                                + bike.TopSpeed + "\n");
            }
            return myBikeList;
        }

I am using inheritance if it makes it easier for you to figure out how to solve this problem.

Thanks guys

Joe

Dani AI

Generated

Short summary and practical fixes.

The thread contained two separate mistakes: ownership/scope of the data, and where ToString should be used. was right to point at scope; was right to suggest not declaring the accumulator inside the loop; and ’s final fix (use an instance ToString and call the base fields) is the usual, clean approach.

Guidelines and patterns to apply

  • ToString should describe a single instance. Keep it lightweight and side-effect free. If you need a combined representation of many vehicles, build that outside the instance method (a presenter/helper or the caller).
  • Don’t instantiate a fresh list inside ToString (that will be empty). Either use the object’s existing fields or accept the collection as a parameter to a separate method.
  • For readable, efficient concatenation use either StringBuilder or join the instances’ ToString results.

Example patterns (not copies of the forum snippets)

// in Vehicle
public override string ToString()
{
    return string.Format("[VEHICLE] {0} {1} {2}", VehicleRegistration, Make, Model);
}

// in a subclass
public override string ToString()
{
    return base.ToString() + " Colour: " + Colour;
}

Combine a list safely:

// using System.Linq;
string all = string.Join(Environment.NewLine, myList.Select(v => v.ToString()));

Troubleshooting checklist

  • Put a breakpoint and inspect the list: is it null? empty? populated elsewhere?
  • Check where the list is created; avoid shadowing a field with a local empty list.
  • Prefer instance ToString for single-object formatting and a separate helper for lists.

This keeps code clear, avoids the scope/empty-list trap you hit, and produces predictable, testable string output.

Recommended Answers

All 5 Replies

Hi

The reason for the error "myBikeList does not exist in the current context" is a matter of scope. At the moment, you have declared the myBikeList variable within the foreach loop, once that loop is completed, the myBikeList variable will be out of scope so not available to code outside of that loop.

Also, even if it was available, with the current code, it would only contain the last vehicle details as you are creating a new string each time so destroying the previous one.

Finally, I notice that you are overriding the ToString method so am wondering if you are doing this within your Vehicle class or some other class. If it is some other class that takes a list of vehicles then fine, if it isn't though, then this may not be the right approach.

HTH

Well I have this now but it simply just returns the empty string? Any ideas?

public override string ToString()
{
    List<Vehicle> myList = new List<Vehicle>();
    string carList = "";

    foreach (Motorbike bike in myList)
    {
        carList = carList + "[CAR]: " + bike.VehicleRegistration + " " + bike.EngineSize
                                + " " + bike.Make + " " + bike.Model + " " + bike.EngineSize + " "
                                + bike.TopSpeed + "\n";
    }
    return carList;// +"MOTORBIKE";
}

Where is this method located? Is it in the Vehicle class?

Have you tried putting a breakpoint on the foreach line and stepping through? My guess is that there is no data in the myList which looking at your code makes sense as you are not assigning anything to myList, you are just declaring it, so therefore it will be an empty list.

Can you post the full class that this method belongs too?

Hi Joe:
Without seeing the entire code, my first guess is that the "myBikeList" variable is out of scope. You might want to define it outside the foreach loop

Tekkno

Hi guys, got the solution. Here is the code. Silly me. Haha, thanks for the help.

Its not suppose to have the foreach loop and I can call to the base class in the deriving class with the base term and then just call the derived class's own property which is in this case this.Colour. Its working now.

public override string ToString()
{
    string carList = ("[CAR]: " + base.VehicleRegistration + " " + base.EngineNumber
                                + " " + base.Make + " " + base.Model + " " + base.EngineSize + " "
                                + this.Colour + "\n");

    return carList;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.