0

I have a class that I'd like to be generic in that I can specify the property to retrieve from the object at runtime. The reason for this is that we have a database table accessed via Entity Framework that has many columns such as,

  1. table.name1
  2. table.name2
  3. table.name3
    .
    .
    .

Terrible legacy table notwithstanding, I'd like to do something similar to the following while allowing for either indexing or straight-out specifying the object property.

public string Name
{ 
    get { return name<#>; } 
}

Thanks!

McArthey
  • 1,614
  • 30
  • 62
  • So, you know that you need to use reflection. What is the real problem? – Sparrow Aug 09 '17 at 19:48
  • I'm struggling with how to best specify the index efficiently at runtime. Instantiate the class with an index parameter? That seems ugly. – McArthey Aug 09 '17 at 19:52
  • Why index? Can't you pass the property name? Using reflection, you can get the list of all properties of the class (names) and get or set properties using the property name – Sparrow Aug 09 '17 at 19:55
  • here is an example: http://www.csharp-examples.net/reflection-property-names/ – Sparrow Aug 09 '17 at 19:57
  • Also, look at this: https://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp – Sparrow Aug 09 '17 at 19:58
  • Thanks. I'm just trying to avoid the hardcoding of the property name because there are many that have a similar naming convention in our database. – McArthey Aug 09 '17 at 20:00
  • Are you trying to create the class dynamically at runtime? If so, look at this one: https://stackoverflow.com/questions/3862226/how-to-dynamically-create-a-class-in-c – Sparrow Aug 09 '17 at 20:02
  • Yes, essentially. It's difficult to represent the complexity with an example but basically there are multiple tables involved so the top-level class uses generics to determine the data object. Therefore I was considering passing in an index along with the generic type. – McArthey Aug 09 '17 at 20:06

0 Answers0