jessi
jessi

Reputation: 1

Access a return parameter type array of a method

I have a class Cars and in the method get_cars() I create multiple Cars and return them as an array cars. In my class Home, I have the method main() where I want to work with the array "cars". In the example I just want to write the name of every car. But it seems like the name attribute is empty. What did I do wrong?

class Car
{
    //only one attribute for test
    public string name;
    // public string color;
    // public string brand;

    public car()
    {
    }

    //create multiple Car, limited to 2 for the test und return them in an array
    public static Car[] get_cars()
    {
        Car[] cars = new Car[2];
        for (int k = 0; k<cars.Length; k++)
        {
            cars[k] = new Car();
            cars[k].name = "Car 0" + k;
        }
        return cars;
    }
}

class Home
{
    private void Main()
    {
        Car[] cars = new Car[2];
        cars = Car.get_cars();

        cars[0] = new Car();
        //the output is empty, it seems that cars[0].name is emtpy;
        set_label_header(cars[0].name);

        cars[1] = new Car();

        //the output is empty, it seems that cars[1].name is emtpy;
        set_label_header(cars[1].name);

        //that works
        set_label_header("test");
    }
}

Upvotes: 0

Views: 94

Answers (3)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

But it seems like the "name" attribute is empty

It's because of the following line:

cars[0] = new Car();

The new Car() creates a fresh object with a clean slate and you only set its id, so name is empty. From the get_cars method you are already returning the objects instantiated, so you don't need to instantiate again.

You actually don't need to new it up.

The following code is fair enough for your case:

Car[] cars = Car.get_cars();

and then call your method :

set_label_header(cars[0].name);

Upvotes: 6

CoolBots
CoolBots

Reputation: 4869

You're re-creating the objects in your array with the new command. Change your Main method as follows:

void Main() 
{ 
    Car[] cars = Car.get_cars();
    set_label_header(cars[0].name);
    set_label_header(cars[1].name);
}

Upvotes: 1

&#214;mer Baş
&#214;mer Baş

Reputation: 98

You are generating new empty Car object here:

cars[0] = new Car();
cars[1] = new Car();

You should access the cars array directly without creating new object.

cars[0].name

Upvotes: 2

Related Questions