How can I access to the properties of List<T>
,where T every time is another type of object, Student, Product, etc.? The problem is that at the compile time C# can't recognize the properties which are included in the T. As you can see (as it's commented in the code) I make foreach
, where after that when I try itemList
, the properties from the object aren't shown.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentLinq {
public class Student {
public int Id {
get;
set;
}
}
public class Admin {
public string Name {
get;
set;
}
}
public class Generic {
public void Print<T>(List<T> list) {
foreach(var itemList in list) {
if (list is List<Student>) {
Console.WriteLine(itemList);
}
//How can I print the properties from the product class and student
}
}
}
class Program {
static void Main(string[] args) {
var studentsList = new List<Student>();
studentsList.Add(new Student {
Id = 2
});
var productList = new List<Product>();
productList.Add(new Product {
Price = 40
});
var generic = new Generic();
generic.Print<Student>(studentsList);
generic.Print<Product>(productList);
Console.ReadLine();
}
}
}