and thanks for any assistance.
How would I return from a method an unknown Generic.List type.
public void Main() { List<A> a= GetData("A"); } public List<T> GetData(string listType) { if(listType == "A") { List<A> a= new List<A>() ... return a; } else { List<B> b = new List<B>() return b; } }
In the below example I recieve an error similar to: Can't Convert List<A>
to List<T>
Is this possible? The error occurs on the 'return a;' line of code.
Also, What will I need to do to make sure an error does not occur on the line:
List<A> a= GetData("A");
Thanks, Steven
You can declare variant generic interfaces by using the in and out keywords for generic type parameters. ref , in , and out parameters in C# cannot be variant. Value types also do not support variance. You can declare a generic type parameter covariant by using the out keyword.
So, to return a null or default value from a generic method we can make use default(). default(T) will return the default object of the type which is provided.
A generic interface is primarily a normal interface like any other. It can be used to declare a variable but assigned the appropriate class. It can be returned from a method. It can be passed as argument.
It's often useful to define interfaces either for generic collection classes, or for the generic classes that represent items in the collection. To avoid boxing and unboxing operations on value types, it's better to use generic interfaces, such as IComparable<T>, on generic classes.
Use IList
instead of List<T>
.
An alternative to being limited to returning a list of objects would be to either ensure that A and B derive from a common base type or implement a common interface, then return a list of that base type or interface. Include a constraint on the Generic method to that effect:-
List<ICommon> GetData<T>() where T: ICommon { }
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