Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Declaring and using a list of generic classes with different types, how?

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.

like image 960
Stécy Avatar asked Feb 26 '09 13:02

Stécy


1 Answers

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:

public class MyData<T, C>     where T : IData<C> {     public T Data { get; private set; }      public MyData (T value)     {          Data = value;     } }  public interface IData<T> {     T Data { get; set; }     void SomeMethod(); }  //you'll need one of these for each data type you wish to support public class MyString: IData<string> {    public MyString(String value)    {        Data = value;    }     public void SomeMethod()    {        //code here that uses _data...        Console.WriteLine(Data);    }     public string Data { get; set; } } 

and then you're implementation would be something like:

var myData = new MyData<MyString, string>(new MyString("new string"));     // Could be MyString, MyInt, ... myData.Data.SomeMethod(); 

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

SomeMethod(myData.Data.Data); 
like image 133
Joseph Avatar answered Oct 04 '22 10:10

Joseph