Rajiv Ganti
Rajiv Ganti

Reputation: 33

C# ArrayList.Add adding by Ref?

I have a base 'Vehicle' class:

public abstract class Vehicle
{
    private string company;
    private string model;

    private static int ID = 0;

    public Vehicle(string company, string model)
    {
        this.company = company;
        this.model = model;
        ID++;
    }

    public override string ToString()
    {
            return "\n\nVehicle Information: \n\t" +
                    "ID: "+ID+"\n\t"+
                    "Car: " + company + "\n\t" +
                    "Model: " + model + "\n\t";
    }
}

Now I have an inherited class 'Ford', inherited from Vehicle:

public class Ford : Vehicle
{
    public Ford(string company, string model) : 
                               base(company, model)
    {

    }        
}

I also have another inherited class 'Honda', inherited from Vehicle:

public class Honda: Vehicle
{
    public Honda(string company, string model) : 
                               base(company, model)
    {

    }        
}

Now in my Main method, I call the derived classes Ford and Honda, and add them to an ArrayList:

class Test
{
    static void Main(string[] args)
    {
        ArrayList vehicleList = new ArrayList();

        Ford firstVehicle = new Ford("Ford", "Fusion");
        vehicleList.Add(firstVehicle);


        vehicleList.Add(new Honda("Honda", "Civic"));


        foreach (Vehicle x in vehicleList)
        {
            Console.WriteLine(x);
        }
    }
}

The problem is that, when I run it, I get the following output:

Vehicle Information:
    ID:2
    Car:Ford
    Model:Fusion
Vehicle Information:
    ID:2
    Car:Honda
    Model:Civic

As you can see, both the objects show the ID column '2' instead of 1 for the first and 2 for the second. When I used the breakpoint to detect whats happening, I see that when the first object is processed, the arrayList shows ID=1 for the first object, but when the second object is processed and added to the arrayList, the ID value of the first object too is changed to 2 from 1. I think this is because it is using 'add by reference'?? any suggestions what can I do to show ID:1 for the first and ID:2 for the second?

Upvotes: 0

Views: 76

Answers (2)

garryp
garryp

Reputation: 5776

ID is static, therefore a singleton. There is one instance of it for the application (shared by all instances of Vehicle)

Start by changing this:

private static int ID = 0;

To this:

private static intCounter = 0;
private int ID = 0;

Then where your ID is being set replace:

ID++;

...with...

intCounter++;
ID = intCounter;

Upvotes: 1

Mike Makarov
Mike Makarov

Reputation: 1356

private static int ID = 0;
private int instanceID;
public Vehicle(string company, string model)
{
    this.company = company;
    this.model = model;
    instanceID = ID++;
}

...and use instanceID in ToString().

Upvotes: 0

Related Questions