I have a web method which calls a method in the DAL to execute a procedure by id and returns an object of type MyData.
[WebMethod]
public MyData GetDataById(int id)
{
DAL myDAL = new DAL();
return myDAL.GetDataById(id);
}
The class MyData looks like the following
public class MyData
{
public string Name;
public Data[] DataItems;
}
and the class Data,
public class Data
{
public string key;
public string value;
}
Now this worked fine for until we wanted to return a bit of complex types.
For an example, a DataTable, or perhaps something like a structure (or class) containing latitude, longitude and a value. So obviously, class Data cannot hold multiple values or a DataTable. (It contains two strings, key and value).
So what I actually want is the type to be Generic. So I changed it to…
public class MyData<T>
{
public string Name;
public T[] DataItems;
}
So I’ll be doing something like this inside the myDAL.GetDataById because what type of data is returned differs according to the type.
if (GetTypeOfId(id) == "NormalData")
{
MyData<Data> result = new MyData<Data>();
}
else if (GetTypeOfId(id) == "Map")
{
MyData<MapData> result = new MyData<MapData>();
}
But I need to specify a type for the method signature as well which unfortunately is found out ONLY at run time.
How do I handle such a situation ?
I feel like I am using Generics for something I shouldn’t be using it for.
Or how is usually a situation where the type is found out only at run time resolved?
UPDATE: The worst case scenario is having different web service calls for getting normal data and map data which I would like to avoid.
The answer was pretty easy and stupid of me not to think of it before.
I just created a parent class and made the
Dataand all the other required classes inherit from it.