Hi @David Gray , Welcome to Microsoft Q&A,
In C#, generic methods cannot identify the actual types of type parameters at compile time, so it is not feasible to use list.GetType() directly inside a generic method to determine the generic type. For your scenario, one possible approach is to use the is keyword to check the type of each element and then perform the appropriate operation. The specific code is as follows:
void Main()
{
var listOfCars = new Car().GetCars();
var listOfCartoons = new Cartoon().GetCartoons();
ShowLists(listOfCars);
ShowLists(listOfCartoons);
}
public static void ShowLists<T>(List<T> list)
{
foreach (var item in list)
{
if (item is Car car)
{
Console.WriteLine($"Car: {car.Manufacturer}, {car.Model}, {car.Country}");
}
else if (item is Cartoon cartoon)
{
Console.WriteLine($"Cartoon: {cartoon.Title}");
}
}
}
public class Car
{
public string Manufacturer { get; set; }
public string Model { get; set; }
public string Country { get; set; }
public List<Car> GetCars()
{
var cars = new List<Car>();
cars.Add(new Car() { Manufacturer = "VW", Model = "Phaeton", Country = "Germany" });
cars.Add(new Car() { Manufacturer = "Land Rover", Model = "Range Rover Sport", Country = "UK" });
return cars;
}
}
public class Cartoon
{
public string Title { get; set; }
public List<Cartoon> GetCartoons()
{
var cartoons = new List<Cartoon>();
cartoons.Add(new Cartoon() { Title = "Family Guy" });
cartoons.Add(new Cartoon() { Title = "Americaan Dad" });
return cartoons;
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.