0

I have a custom class defined:

class Car
{
    public string a;
    public string b;
    public string c;

    public static void GetCar()
    {
        var car = new Car[4];
        for(int i=0; i<4; ++i)
        {
            novica[i]= new Novica();
            novica[i].a="abc";
            novica[i].b="abc";
            novica[i].c="abc";
        }

    }
}

This fills the array with values, and now I would like to use this array with the values it gets (loading string from HTML) in a function that is not part of this class. Is it possible and if so, how?

3
  • 2
    You need to be more elaborate in specifying what you want. Commented Dec 26, 2012 at 17:52
  • I imagine you actually want car[i] = new Novica(); etc. Commented Dec 26, 2012 at 17:56
  • Sorry about novica - it's supposed to be car there. Copy and paste:D Commented Dec 26, 2012 at 17:57

3 Answers 3

5

In order to use it elsewhere, you would need to return the array from your function, like so:

public static Car[] GetCar()
    {
        var car = new Car[4];
        for(int i=0; i<4; ++i)
        {
            car[i]= new Novica();
            car[i].a="abc";
            car[i].b="abc";
            car[i].c="abc";
        }

        return car;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

This looks right. I think he wants to return novica though.
2

You can't. Your method doesn't actually return anything.

If you were to change the method signature to return the array the method creates:

public static Car[] GetCar()
{
    // Body

    return car;
}

The call would become as simple as:

var cars = Car.GetCar();

Comments

0

I suggest a slightly different construction. Provide an array containing all cars as static property

public class Car
{
    public static Car[] AllCars { get; private set; }

    public Car()
    {
        // Class and constructor somewhat simplyfied.
        AllCars = new Car[4];
        for (int i = 0; i < 4; ++i) {
            AllCars[i] = new Novica();
        }
    }
}

Now you can work with cars like this

foreach (Car car in Car.AllCars) {
    // do something with car
}

Or access a specific car with

string a = Car.AllCars[i].a;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.