When I read a cell by doing Worksheets.Cells[2,5].value.ToString();
I get a error "System.NullReferenceException: Object reference not set to an instance of an object."
What would be a good way to check for null and then assign the value, without having to have a "if" statement.
So, a reference is what a variable of a reference type contains. These variables can point to “nothing”, though, and that's what we call a null reference: a reference that doesn't point to any object. When you try to call a method or another member on the said variable, you got the NullReferenceException.
The message "object reference not set to an instance of an object" means that you are referring to an object the does not exist or was deleted or cleaned up. It's usually better to avoid a NullReferenceException than to handle it after it occurs.
string strValue = Worksheets.Cells[2,5].value==null ? string.Empty : Worksheets.Cells[2,5].value.ToString();
or
object objValue = Worksheets.Cells[2,5].value ?? string.Empty
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With