C# Check if object exists before referencing -
this question has answer here:
- what nullreferenceexception, , how fix it? 29 answers
i wondering if there's way check if object exists before referencing @ all. not check if null because isn't working either. using epplus package read excel files , when gets index not have value data in it, sends exception.
private datatable worksheettodatatable(string tablename) { excelsheet = excelworkbook.worksheets[tablename]; datatable dt = new datatable(); try { int totalrows = excelsheet.dimension.end.row; int totalcols = excelsheet.dimension.end.column; (int j = 1; j <= totalcols; j++) { dt.columns.add(); (int = 1; <= totalrows; i++) { if (j == 1) { dt.rows.add(); } try { dt.rows[i - 1][j - 1] = excelsheet.cells[i, j].value.tostring(); //dt.rows[i - 1][j - 1] = object.referenceequals(null, excelsheet.cells[i, j].value.tostring()) ? "" : excelsheet.cells[i, j].value.tostring(); } catch { dt.rows[i - 1][j - 1] = ""; } } } return dt; } catch { messagebox.show("error: referenced excel table empty, or indexed improperly! check excel formatting.", "error"); return dt; } }
so can see i've tried checking if excelsheet.cells[i, j].value.tostring()
null before , sends same exception caught in try/catch have above. have parse lot of cells , lot of them empty, adds lot of
exception thrown: 'system.nullreferenceexception' in bbsapp.exe
to output console. there way check if object exists before call object check if null without try/catch?
if(excelsheet.cells[i, j].value.tostring() != null)
simply checking if null shown above sends same exception because not exist in first place.
try this:
if(excelsheet.cells[i, j].value != null)
you're checking see value
property null. null reference exception occurs because trying call method tostring()
on null
object.
alternatively, can use null access operator:
if(excelsheet.cells[i, j]?.value?.tostring() != null)
Comments
Post a Comment