Subscripts (indexer methods) with multiple parameters in C#
Forums:
class Car {
public string Model { get; set; }
public int Year { get; set; }
public int Price { get; set; }
public Car(string model, int year, int price) {
Model = model;
Year = year;
Price = price;
}
}
class ToyotaPrices {
private List<Car> Cars = new List<Car>();
public int this[string model, int year] {
get {
var car = FindCar(model, year);
if (car == null)
return 0;
return car.Price;
}
set {
var car = FindCar(model, year);
if (car == null) {
car = new Car(model, year, value);
Cars.Add(car);
}
else
car.Price = value;
}
}
private Car FindCar(string model, int year) {
return Cars.SingleOrDefault(
c => c.Model == model && c.Year == year);
}
}
var prices = new ToyotaPrices();
prices["Rush", 2012] = 16818;
prices["Land Cruiser", 2014] = 54988;
var priceRAV4 = prices["RAV4", 2015];
//priceRAV4 is 0
var priceRush = prices["Rush", 2012];
//priceRush is 16818
- Log in to post comments