Thanks Viorel-1 for your suggestion.
I have to explain it again a little more precisely because this was misunderstood.
- I have a function (WebApi) that gets as parameter the class name from client app
public static async Task<IResult> GetMyData(string className)
{
.
}
- in the function I then call a generic method that returns me the result:
public static async Task<IResult> GetMyData(string className)
{
DataTable tblRes = new DataTable("tbl");
tblRes = await mssql.GetData("SELECT ....");
List<T> list = new List<T>();
foreach (DataRow row in tblRes.Rows)
{
T item = mssql.GetItem<T>(row);
list.Add(item);
}
return await Task.FromResult(Results.Ok(list));
}
- Here the problem is that the List need data type and generic method GetItem expects also a data type (class) < T >.
- originally I tried to determine the class via Activator, but this triggers compiler error CS0118 because of T
public static async Task<IResult> GetMyData(string className)
{
Type temp = Type.GetType(className);
var T = Activator.CreateInstance(temp);
DataTable tblRes = new DataTable("tbl");
tblRes = await mssql.GetData("SELECT ....");
List<T> list = new List<T>();
foreach (DataRow row in tblRes.Rows)
{
T item = mssql.GetItem<T>(row);
list.Add(item);
}
return await Task.FromResult(Results.Ok(list));
}
I have a workaround and it looks like this:
- I don't use a generic method
public static async Task<IResult> GetMyData(string className)
{
.
.
object item = mssql.GetItem(row, className);
list.Add(item);
.
.
return await Task.FromResult(Results.Ok(list));
}
- I pass the class name to the method . Return value is then an object (because I don't have a T).
- in the method I can do what you suggest:
public object GetItem(DataRow dr, string classname)
{
Type temp = Type.GetType(classname);
var obj = Activator.CreateInstance(temp);
.
.
return obj;
}
The workaround works, but I would have preferred to solve it via T because it seems cleaner to me.
Does anyone have any ideas?
Thanks
EDIT
The background is that I have a very large number of models (classes). So I can create an endpoint for each model in the WebApi, then I can also write out the class (e.g. if I want to fetch all products, I put the class "Products"):
List<Products> list = new List<Products>();
foreach (DataRow row in tblRes.Rows)
{
Products item = mssql.GetItem<Products>(row);
list.Add(item);
}
Or I can do this generically, then I only need to program one endpoint in the WebApi, but can use it to address all classes by passing the class name from Client to WebApi and using generic methods in the WebApi. So for this to work, I need to get a real class from a class name (So I need to convert className to < T > ).