I’ve run into a little difficulty and I’m not sure how best to solve this issue.
I wrote a class that expects data type to be specified upon the creation of a new instance. Much like in the same way as the System.Collections.Generic.List<T> class that stores a number of items of a specified type. However my class doesn’t has the same or similar function as the List<T> class does.
Upon creation of a new instance of my class, for example:
string phrase = "Some string type data.";
MyClass<string> data = new MyClass<string>( () => phrase );
Afterwards my class would provide a number of methods that would give a result regardless of the type of data being imparted into MyClass<T> (where T is the data type). Doesn’t matter if it is string, bool, int, or any kind.
I’ve tested my class and it works as expected, now how can I store a number of elements of MyClass but each element with different imparted data type, inside a collection class such as List<>.
Let me exemplify (code will contain syntax errors since I’m not sure how to write correctly):
// My intent... Not sure how to do it.
string phrase = "Some string data type.";
int number = 23;
bool boolData = false;
List<MyClass<T>> list = new List<MyClass<T>>();
list.Add( new MyClass<string>( () => phrase ) );
list.Add( new MyClass<int>( () => number ) );
list.add( new MyClass<bool>( () => boolData ) );
As you see I don’t know how to store a number of element of MyClass with different imparted data types, if they were all the same imparted data type, I wouldn’t be having this issue.
For example:
// How it should be done. But not what I need.
string phrase1 = "Hello Phrase 1.";
string phrase2 = "Hello Phrase 2.";
List<MyClass<string>> list = new List<MyClass<string>>();
list.Add(new MyClass<string>( () => phrase1) );
list.Add(new MyClass<string>( () => phrase2) );
If this was what I wanted to accomplish, I wouldn’t have a problem, but since I want to accomplish what I exemplified before this last example, I’m just not sure how to best do it.
Basically thats my issue, I’ve provided a few basic examples because I believe my question might be a bit odd, and to be honest my terminology wouldn’t not be adequate I think.
This is probably quite simple for some of you. My thanks for your help.
Typically you’d create a non-generic base class (or interface) for the generic type:
Then you can just create a
List<MyClass>. Of course to get at any of the members withinMyClass<T>you’ll need to know the rightTto cast to, but I think that’s unavoidable.Of course this doesn’t help much if you don’t control
MyClass<T>and it doesn’t provide a useful base class – but there’s nothing in C# to help you with this situation.