Sadeep Sadeep - 4 months ago 22
C# Question

Return null to avoid unknown exceptions from a method in C#

I have the following method that opens a Excel workbook and returns it to be used in another method.

private Excel.Workbook openWorkbook()
{
// Get excel file path returns the file path of the excel workbook if it exists, otherwise returns null.
List<string> filePaths = getExcelFilePath();
if (filePaths != null)
{
return excel.Workbooks.Open(filePaths[0]);
}
return null;
}


As you can see, I'm returning
null
to avoid a
try-catch
for a non-exixtent workbook when I call this from another method. Is it bad practice to do this. I do a similar thing in the following method which is supposed to return a list:

private List<string> getSOsToDelete()
{
// rawData is private variable in the class. If the workbook was not open this worksheet is set to null in another method similar to openWorkbook() above.
if (rawData != null)
{
List<string> ToDeleteSOs = new List<string>();
for (int i = rawData.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row; i > 1; i--)
{
if (rawData.Cells[i, 7].Value2.ToString() != "B2B" || rawData.Cells[i, 7].Value2.ToString() != "" || rawData.Cells[i, 8].Value2.ToString() != "Trns-Inc" || rawData.Cells[i, 8].Value2.ToString() != "")
{
string SONumber = rawData.Cells[i, 3].Value2.ToString();
ToDeleteSOs.Add(SONumber);
}
}
return ToDeleteSOs;
}
return null;
}


If not so, what is the best way to write methods like these? For part 2 I guess I could return an empty list and check for length. I'm not sure which is better. However, for first method, I'm really not sure what to return if the file doesn't exist.

Answer

I think there is no hard and fast rule for this. But I would return null from first method as returning a null where there is no workbook seems meaning full as null represent no object but from second method empty list would be a batter option as with list we used to use Count before using it instead of null or iterate over list etc. This also goes with convention like ToList will return list of zero elements instead of returning null.

Return null to avoid unknown exceptions from a method in C#

There could be different way to tell the caller method that error occurred in called method and exception is one of those and widely adopted. You can document the method to tell when kind of exception are expected from the method. Lets look at documentation of String.Substring Method (Int32, Int32) on MSDN. The documentation mentions that this method could through ArgumentOutOfRangeException when startIndex plus length indicates a position not within this instance, or startIndex or length is less than zero, MSDN

Comments