somya rawal

somya rawal

  • NA
  • 4
  • 429

Pass Generic Object Dynamically

Apr 20 2018 5:17 PM
I am trying to dynamically show a table depending on what tableName user has selected from dropdown. I am passing a json object from my web Controller(.Net Core) so in order to do it, I am first converting my dataTable to list of objects using function
  1. public static List<T> ConvertTableToList<T>(this DataTable table) where T : classnew()  
  2. {  
  3. try { List<T> list = new List<T>();  
  4. foreach (var row in table.AsEnumerable())  
  5. {  
  6. T obj = new T();  
  7. foreach (var prop in obj.GetType().GetProperties())  
  8. {  
  9. try { PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);  
  10. propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);  
  11. }  
  12. catch(Exception ex)  
  13. {  
  14. throw ex;  
  15. }  
  16. }  
  17. list.Add(obj);  
  18. }  
  19. return list;  
  20. }  
  21. catch { return null; }  
  22. }  
and call this function in my Get Request
  1. public IActionResult GetTableDetailsByTableName(string TableNameSelected)  
  2. {  
  3. //To get the data for the Table Selected DataTable  
  4. TableDetails = ReferenceTableLogics.getTableDetails(TableNameSelected);  
  5. var TableDetailsInList = ConverterClass.ConvertTableToList<CSBM_AGE_BAND>(TableDetails);   
  6. return Ok(TableDetailsInList);  
  7. }  
Now the issue is that I need to tell my class Name (eg CSBM_AGE_BAND in this case) depending on what user has selected in dropdown (TableNameSelected).
Is there any way by which I can dynamically pass this class name to my function ConvertTableToList() ?