Alex Rivera | Logout

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

Asked 2009-02-26T13:27:40.050
29

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.

Edit
Report

1 Answer

0

Generics allow you to specify one type for the whole list when you create the list, for example a list for storing int would be created like this

var myData = new MyData<int>();

If you want to store multiple types in the same generic list you can specify a common base type or interface for those types. Unfortunately in your case the only common base type for the types you want to store would be object.

var myData = new MyData<object>();

But you can just use the non-generic list for storing objects.

answered 2009-02-26T13:32:29.680

Your Answer