Search code examples
c#genericscollectionsreturn

Returning generic lists from methods in C#


I'm having a difficulty returning a generic collection from a Linq Extension. I call the method with a single parameter:


   static List<NewPeople> GetPeople()
           {
               List<People> ppl = Enttity.GetCollection();
               var abc = new List<NewPeople>();
               ppl.CopyAllTo(abc);

               return abc;
               //return nppl;
           }

Called Method:



   public static IList<U> CopyAllTo<T, U>(this IEnumerable<T> source, List<U> destination) 
                   where T : class 
                   where U : class
           {
               List<U> objectList = new List<U>();
               foreach (T t in source)
               {
                   U u = Activator.CreateInstance<U>();
                   t.CopyTo(u);
                   objectList.Add(u);
               }

               return objectList;
           }

I can't get the list to return. When I break code on "return ObjectList", there are 3 objects in the list, however, on return to the caller, a null value is returned.

Does anyone know what's wrong with this picture?


Solution

  • Either you'll have to assign the value to abc in your GetPeople method (remove the destination argument in your CopyAllTo method):

    static List<NewPeople> GetPeople()
    {
        List<People> ppl = Enttity.GetCollection();
        List<NewPeople> abc = ppl.CopyAllTo<People,NewPeople>();
    
        return abc;
        //return nppl;
    }
    

    Or you use the destination variable in your CopyAllTo method (this is possible because List<T> is a reference type):

    public static void CopyAllTo<T, U>(this IEnumerable<T> source, List<U> destination) 
        where T : class 
        where U : class
    {
        foreach (T t in source)
        {
            U u = Activator.CreateInstance<U>();
            t.CopyTo(u);
            destination.Add(u);
        }
    }