简体   繁体   中英

C# VSTO - Checking if a cell is empty using String.Empty

I have inherited a C#-based VSTO project where a lot of data is read from a spreadsheet and then processed. A lot of places in the code I'm seeing the following:

(((Excel.Range)sheet.Cells[rowIndex, columnIndex]).Value2 != null 
    && ((Excel.Range)sheet.Cells[rowIndex, columnIndex]).Value2.ToString().Length > 0)

This snippet checks that a cell contains a value before copying out the value which is fine. But won't checking against String.Empty do the same in one line instead of two, or are there cases where that will fail despite having a value in the cell?

Nevermind, I figured it out. Checking on:

(((Excel.Range)sheet.Cells[rowIndex, columnIndex]).Value2.ToString() != String.Empty

fails if the cell I'm doing .ToString() on happens to be empty in the first place. Checking on .value2 != String.Empty will also fail if Excel regards the cell as having a formatting other than a string.

I'd suggest starting from breaking the chain of property and method calls and declaring each of them on a separate line of code. Thus, you will be able to identify the cause of the issue, if any. Also you will be able to release underlying COM objects instantly. Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Outlook object when you have finished using it. The set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object. You can read more about that in the Systematically Releasing Objects article in MSDN. It is related to Outlook, but the same rules can be applied to any Office application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM