Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return empty List in catch block

I have a c# function that reads file locations from a Datatable, and returns a List with all the file lcoations to the calling method.

In the Catch block, I want to return an empty list with a false so teh calling method can cancel it's operation.

But I can't get my return statement to compile.

Would it be better to pass in a list as a refernce, and have the function return a boolean true/false?

here is the code I am trying:

   public static List<string> getEmailAttachments(string emailID, System.Data.DataTable emails)
    {
        List<string> allAttachments;

        //System.Data.DataTable oTbl = new DataTable();
        try
        {
            System.Diagnostics.Debugger.Break();

            var results = from myRow in emails.AsEnumerable()
                          where myRow.Field<string>("itemID") == emailID
                          select myRow;

            System.Diagnostics.Debug.Print("attachments");
            foreach (DataRow myRow in results)
            {
                System.Diagnostics.Debug.Print(myRow.Field<string>("attachmentsPath"));
                allAttachments.Add(myRow.Field<string>("attachmentsPath"));

                //DataTable dt = (DataTable)myRow["attachmentsPath"];
                //DataTable oTbl = dt.Clone();

                //DataRow[] orderRows = dt.Select("CustomerID = 2");

                //foreach (DataRow dr in orderRows)
                //{
                //    oTbl.ImportRow(dr);
                //}
                // myTable.ImportRow(dr);
                //oTbl.Rows.Add(myRow);
                //oTbl.ImportRow(myRow);
            }

            return allAttachments;
        }
        catch (Exception ex)
        {
            logBuilder("common.getEmailAttachments", "Exception", "", ex.Message, "");

            return new List<string>emptyList(); // cannot compile
        }
    }
like image 825
Our Man in Bananas Avatar asked Apr 11 '14 09:04

Our Man in Bananas


1 Answers

I would take a slightly different approach. I would return an empty list but ALSO set the initial capacity to ZERO!

Like this:

return new List<string>(0);//notice the initial capacity to zero.

The reason is for memory consumption and optimization... I know it is a micro optimization but it won't hurt anything. It might actually benefit the overall application.

like image 200
Jonathan Alfaro Avatar answered Oct 20 '22 14:10

Jonathan Alfaro