Setting variable the error Cannot perform runtime binding on a null reference

1

I'm running the below C# code :

Excel.Workbook s_workbook = sApp.Workbooks.Open(s_file);
Excel._Worksheet s_ws = s_workbook.Worksheets[1];
string strst = s_ws.Cells[17][1].Value.ToString();

But I get this error when setting the variable strst in the last line in my above code:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
  HResult=0x80131500
  Message=Cannot perform runtime binding on a null reference
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

I tried doing this string strst = s_ws.Cells[17][1].Value.Convert.ToString(); but I get the same error. Any advice?

c#
.net
asked on Stack Overflow Jan 11, 2021 by Tak • edited Jan 12, 2021 by Salah Akbari

1 Answer

2

It seems either the Value or Cells[17][1] are null, you can try something like this:

string strst = s_ws.Cells[17][1]?.Value?.ToString();

It is called Null-conditional operator.

The null-conditional operators are short-circuiting. That is, if one operation in a chain of conditional member or element access operations returns null, the rest of the chain doesn't execute.

answered on Stack Overflow Jan 11, 2021 by Salah Akbari • edited Jan 11, 2021 by Salah Akbari

User contributions licensed under CC BY-SA 3.0