I have created a class called AirlineCompany which attribute have a collection of flight information. To have flight information, I created a class called Flight. Then in the AirlineCompany I created a indexer with type list for Flight, I also create a setter for it. In the main I tried to set value for the list but keep receive exception when running the code.
This is my class Flight:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment3
{
class Flight
{
private int id;
public int Id
{
get { return id; }
set { this.id = value; }
}
private string origin;
public string Origin
{
get { return origin; }
set { this.origin = value; }
}
private string destination;
public string Destination
{
get { return destination; }
set { this.destination = value; }
}
private string date;
public string Date
{
get { return date; }
set { this.date = value; }
}
private double price;
public double Price
{
get { return price; }
set { this.price = value; }
}
public Flight(int id, string origin, string destination, string date, double price) {
this.id = id;
this.origin = origin;
this.destination = destination;
this.date = date;
this.price = price;
}
public bool FindFlight(int searchId)
{
if(searchId == this.id)
{
return true;
}
return false;
}
public override string ToString()
{
string s = "Flight ID: " + id + "\nOrigin: " + origin + "\nDestination: " + destination +
"\nDate: " + date + "\nPrice: " + price + "$";
return s;
}
}
}
This is my AirlineCompany class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment3
{
class AirlineCompany
{
public static readonly string airlineName;
static AirlineCompany()
{
airlineName = "Vietjet airline";
}
public List<Flight> flights= new List<Flight>(100);
public Flight this[int index]
{
set
{
flights.Insert(index, value);
}
get
{
return flights[index];
}
}
}
}
This is my main class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment3
{
class Program
{
static void Main(string[] args)
{
AirlineCompany vn = new AirlineCompany();
Console.WriteLine(AirlineCompany.airlineName);
vn.flights[0] = new Flight(1,"Viet Nam","Finland","24/11",169.9);
vn.flights[1] = new Flight(2, "Finland", "Singapore", "25/11", 109.9);
vn.flights[2] = new Flight(3, "Singapore", "Finland", "26/11", 129.9);
vn.flights[3] = new Flight(4, "Holland", "Germany", "27/11", 69.9);
Console.ReadLine();
}
}
}
This is the exception when I run code: