I am making a basic Visual Studio project. Easiest way to explain is to show the code.
using System;
using System.Collections.Generic;
namespace testing
{
class Program
{
static void Main(string[] args)
{
int amountOfCars = getAmountOfCars();
Car[] myCars = createCars(amountOfCars);
}
public static int getAmountOfCars (){
Console.WriteLine("Amount of Cars to enter");
int amountOfCars = Convert.ToInt32(Console.ReadLine());
return amountOfCars;
}
public static Car createCars(int amountOfCars)
{
Car[] myCars = new Car[amountOfCars];
for (int i = 0; i < amountOfCars; i++)
{
Console.WriteLine("Enter brand");
string brand = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter amount of wheels");
int amountOfWheels = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter amount of seats");
int amountOfSeats = Convert.ToInt32(Console.ReadLine());
myCars[i] = new Car(brand, amountOfWheels, amountOfSeats);
}
return myCars[amountOfCars];
}
}
}
This line
Car[] myCars = createCars(amountOfCars);
Throws the following error:
Cannot implicitly convert type testing.Car to testing.Car[]
So, I then tried this to convert over
Car[] myCars = (Car[]) createCars(amountOfCars);
But it still throws the error.
Essentially I am just trying to return the array of objects from createcar function, so that it can be used within the rest of the code.
What is the best practice to solve this?
Car createCars(returns a singleCar, not an arrayIndexOutOfRangeException.return myCars[amountOfCars];, since it appears you're appear to have an "off by one" error. The last element in the array ismyCars[amountOfCars-1];