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#?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With