Cannot perform runtime binding on a null reference on C# String.IsNullorEmpty in VS2019

6.7k Views Asked by At

I use the String.IsNullorEmpty to check if a cell in Excel worksheet is null or empty. Why VS2019 still reports a error if the cell is empty? I am sure the worksheet wshIO exists and the intRowIO is 1 when this error came out. The code associated with this worksheet before this line works very well. enter image description here

1

There are 1 best solutions below

2
On BEST ANSWER

You are calling ToString on (potentially) a null dynamic type.

For instance, it's the same scenario as the following:

dynamic s = null;
s.ToString(); // Cannot perform runtime binding on a null reference

One fix is to use the null conditional operator, which will check the dynamic type for null.

string.IsNullOrEmpty(s?.ToString());

Or related to your example:

string.IsNullOrEmpty(something.Cells[x,y].Value2?.ToString())