I want to create a list taking all the values that a property has in a list of certain class and add these values into another list whose type is the same than the class property.
Lets suppose I have the Book class:
public class Book{
public int code;
public string genre;
public string author;
public string synopsis;
}
Then, I have some method with a List<Book> myList containing some books and I want to populate a list of bookCodes which should be of the same type than Book's property code. I want not to change the declaration of the list of BookCodes List<int> myBookCodes if some day the code property is changed from int to long or Guid, for example.
I have tried things such as
var myBookCodes = new List<typeof(Books.code)>
But I get a "Type expected" error.
I have also tried to use reflection but I also got errors:
System.Reflection.PropertyInfo bookCodeProperty = typeof(Book).GetProperty("code");
Type bookCodeType = bookCodeProperty.PropertyType;
var myBookCodes = new List <>(bookCodeType)
But in this case the compiler complains "bookCodeType is a variable but it is used like a type".
Is there a way to do this?