Having the following generic class that would contain either string, int, float, long
as the type:
public class MyData<T>
{
private T _data;
public MyData (T value)
{
_data = value;
}
public T Data { get { return _data; } }
}
I am trying to get a list of MyData<T>
where each item would be of different T
.
I want to be able to access an item from the list and get its value as in the following code:
MyData<> myData = _myList[0]; // Could be <string>, <int>, ...
SomeMethod (myData.Data);
where SomeMethod()
is declared as follows:
public void SomeMethod (string value);
public void SomeMethod (int value);
public void SomeMethod (float value);
UPDATE:
SomeMethod()
is from another tier class I do not have control of and SomeMethod(object)
does not exist.
However, I can't seem to find a way to make the compiler happy.
Any suggestions?
Thank you.
Best Solution
I think the issue that you're having is because you're trying to create a generic type, and then create a list of that generic type. You could accomplish what you're trying to do by contracting out the data types you're trying to support, say as an IData element, and then create your MyData generic with a constraint of IData. The downside to this would be that you would have to create your own data types to represent all the primitive data types you're using (string, int, float, long). It might look something like this:
and then you're implementation would be something like:
it's a little more work but you get the functionality you were going for.
UPDATE: remove SomeMethod from your interface and just do this