Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return unknown Generic List<T>

Tags:

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

like image 373
stevenrosscampbell Avatar asked Feb 26 '09 00:02

stevenrosscampbell


People also ask

How to define generic interface in c#?

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.

How do I return a generic null?

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.

How to define generic interface?

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.

Why use generic interface c#?

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.


2 Answers

Use IList instead of List<T>.

like image 95
John Rasch Avatar answered Sep 27 '22 19:09

John Rasch


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 {  } 
like image 38
AnthonyWJones Avatar answered Sep 27 '22 19:09

AnthonyWJones