BLOG.CSHARPHELPER.COM: Compare car costs including long term mileage in C#
Compare car costs including long term mileage in C#
Some cars that seem less expensive than others actually cost more in the long run because they get worse gas mileage. This example calculates the total cost of a car including gas use. Enter the total number of city and highway miles of driving you expect over the life of the car and the gas price per gallon. Then click the Calculate button to see the results. Click on the ListView's columns to sort by that column.
This example uses the following CarData class to hold information about a car.
private class CarData
{
public string Name;
public float CityMileage, HwyMileage, BaseCost;
public CarData(string name, float city_mileage, float hwy_mileage, float base_cost)
{
Name = name;
CityMileage = city_mileage;
HwyMileage = hwy_mileage;
BaseCost = base_cost;
}
}
private List Cars = new List();
The following code shows how the program calculates and displays the total cost for a car.
This code loops through the CarData objects adding their data to the ListView. It displays the car's name, base cost, city mileage, and highway mileage. It then calculates the car's total cost including fuel costs and displays that.
This program uses the techniques described in the post Make a ListView sort using the column you click in C# to let you sort the columns.
Note that there are many other factors to consider when choosing a car. No one drives a Mercedes-Benz E350 because it saves at the pump.
Also I suspect some of these cars are more likely to last much longer than others. A less expensive car might last around 100,000 or 120,000 miles while a more expensive model might last 200,000 miles. If you factor in the cost of buying a second cheap car, buying the more expensive model may be much cheaper in the long run.
Comments