Reputation: 97
I was trying to display data of class from list in C#.
Here is my class definition:
class Vehicle
{
public string brand;
public string model;
}
class Car : Vehicle
{
double trunk_capacity;
int doors_number;
int vmax;
}
Here is my code in which i'm adding car element:
public static void AddCar(List<object> avaliable_cars)
{
int x = 0;
Console.WriteLine("Adding new car:");
Console.WriteLine("1 - Car");
Console.WriteLine("2 - Sport Car");
Console.WriteLine("3 - Truck");
x = int.Parse(Console.ReadLine());
switch (x)
{
case 1:
{
Console.WriteLine("Adding new Car.");
avaliable_cars.Add(new Car());
Console.WriteLine("Brand");
string brand_tmp = Console.ReadLine();
Console.WriteLine("Model");
string model_tmp = Console.ReadLine();
avaliable_cars.Add(new Car()
{
brand = brand_tmp,
model = model_tmp
});
} break;
}
}
I don't have idea how can i display data from this list.
I was trying to do this
foreach (object car in avaliable_cars)
{
Console.WriteLine(car);
}
I doesn't works. Also i want to access one element at one time - for example i want to display brand of first car on the list. How can i do this?
PS Im beginner in C#, so im sorry for any stupid elements in my code.
Upvotes: 2
Views: 4647
Reputation: 3231
We can simply use String.Join or foreach.
List<string> numbers = new List<string>
{ "One", "Two", "Three","Four","Five"};
Console.WriteLine(String.Join(", ", numbers));
List<string> strings = new List<string> { "a", "b", "c" };
strings.ForEach(Console.WriteLine);
Upvotes: 0
Reputation: 2952
A nice way would be using generics. You could specialize your method AddCar like this:
static void AddCar<T>(List<T> avaliable_cars)
where T : Car ,new()
{
int x = 0;
Console.WriteLine("Adding new car:");
Console.WriteLine("1 - Car");
Console.WriteLine("2 - Sport Car");
Console.WriteLine("3 - Truck");
x = int.Parse(Console.ReadLine());
switch (x)
{
case 1:
{
Console.WriteLine("Adding new Car.");
avaliable_cars.Add(new T());
Console.WriteLine("Brand");
string brand_tmp = Console.ReadLine();
Console.WriteLine("Model");
string model_tmp = Console.ReadLine();
avaliable_cars.Add(new T()
{
brand = brand_tmp,
model = model_tmp
});
} break;
}
}
And to print your data you can simply use T instead of object:
foreach (T car in avaliable_cars)
{
Console.WriteLine(car);
}
Hope it helps.
Upvotes: 1
Reputation: 1493
You need cast the object car to the type Car or Vehicle and then print.
foreach (object car in avaliable_cars)
{
Console.WriteLine(((Vehicle)car).brand);
}
Upvotes: 2
Reputation: 150208
One clean way of doing this is to override ToString()
class Vehicle
{
public string brand;
public string model;
public override ToString()
{
return "Brand: " + brand + ", Model: " + model;
}
}
class Car : Vehicle
{
double trunk_capacity;
int doors_number;
int vmax;
public override ToString()
{
return base.ToString() +
"trunk_capacity: " + trunk_capacity; // etc.
}
}
Then you can simply use
Console.WriteLine(car);
Upvotes: 2