The correct approach would be implement an interface (as @Adarsha has said) and implement RenderOutput() method in each class to have it's own specific implementation with correct list of properties, correct formatting etc.
Now, if you still want to stick to your approach, this is will work.
Let's assume these are your classes
public class Car
{
public string Brand { get; set; }
public int HorsePower { get; set; }
public int TopSpeed { get; set; }
}
public class Driver
{
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
}
Now, these methods will use reflection to read the properties and writethem out in console.
public static void RenderOutput(IEnumerable<object> collection)
{
RenderHeader(collection.First()); //collection not validated
collection.ToList().ForEach(item => RenderBody(item));
}
private static void RenderHeader(object obj)
{
var properties = obj.GetType().GetProperties().OrderBy(p => p.Name);
Console.WriteLine("");
foreach (var prop in properties)
{
Console.Write(prop.Name + "\t"); //or ("{0,15}", prop.Name)
}
}
private static void RenderBody(object obj)
{
var properties = obj.GetType().GetProperties().OrderBy(p => p.Name);
Console.WriteLine("");
foreach (var prop in properties)
{
Console.Write((prop.GetValue(obj, null)) + "\t"); //or ("{0,15}", (prop.GetValue(obj, null)))
}
}
You can now call the RenderOutput()
method on any IEnumerable<T>
to get your desired output. You can test it like this
static void Main(string[] args)
{
//test data
var cars = new List<Car>();
cars.Add(new Car { Brand = "BMW", HorsePower = 100, TopSpeed = 200 });
cars.Add(new Car { Brand = "VW", HorsePower = 90, TopSpeed = 150 });
var drivers = new List<Driver>();
drivers.Add(new Driver { Name = "Prit", Age = 18, Sex = "Male" });
drivers.Add(new Driver { Name = "Jane", Age = 20, Sex = "Female" });
RenderOutput(cars);
Console.WriteLine();
RenderOutput(drivers);
Console.ReadLine();
}
This is the generated output:
Brand HorsePower TopSpeed
BMW 100 200
VW 90 150
Age Name Sex
18 Prit Male
20 Jane Female
Note: This will not work for complex type properties!