Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a Untyped Collection in C#

I am porting some Java code to C# and I ran across this:

List<?>

As I understand it this is a List of type Unknown. As a result I can dictate the type elsewhere (at runtime? I'm not sure).

What is the fundamental equivalent in C#?

like image 792
tzenes Avatar asked Aug 12 '10 00:08

tzenes


2 Answers

I think the best match to Java's List<?> would be C# 4.0 IEnumerable<out T> If you have a method that takes List<?> than you can call it with List<Object> and List<String> like so:

List<Object> objList = new List<Object>();
List<String> strList = new List<String>();

doSomething(objList); //OK
doSomething(strList); //OK

public void doSomething(List<?> theList) {
 ///Iterate through list
}

C# 4.0 IEnumerable<T> interface is actually IEnumerable<out T>, which means that if, say, R derives from T, IEnumerable<T> can be assigned to from IEnumerable<R>.

So, all you have to do is make your doSomething into DoSomething and have accept IEnumerable<T> parameter:

List<Object> objList = new List<Object>();
List<String> strList = new List<String>();

DoSomething(objList); //OK
DoSomething(strList); //OK

public void DoSomething<T>(IEnumerable<T> theList) {
 ///Iterate through list
}

EDIT: If C# 4.0 is not available, you can always fall back to either untyped IEnumerable or IList.

like image 118
Igor Zevaka Avatar answered Nov 10 '22 05:11

Igor Zevaka


If you want a list that can hold anything, you can use a List<object> or an ArrayList.

If you want a strongly-typed list that holds an unknown type, you should make a generic class or method and use a List<T>.

For more specific advice, please provide more detail.

like image 34
SLaks Avatar answered Nov 10 '22 06:11

SLaks