Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid this potential "run-time exception on write operation"?

With this code:

for (int row = 0; row < PlatypusGridRowCount; row++) {
    // Save each row as an array
    var currentRowContents = new string[ColumnCount];
    // Add each column to the currentColumn
    for (int col = 0; col < ColumnCount; col++) {
        currentRowContents[col] = this.GetPlatypusValForCell(row, col);
}
// Add the row to the DGV
dataGridViewPlatypus.Rows.Add(currentRowContents);

Resharper says about the last line: "Co-variant array conversion from string[] to object[] can cause run-time exception on write operation"

So I let it make the change it wants to ("Change type of local variable to object[] ...") so that the code becomes this:

...
    object[] currentRowContents = new string[ColumnCount];
...

Then, when I rerun the Resharper inspection, I get the exact same exact warning message again from Resharper ("Co-variant array conversion from string[] to object[] can cause run-time exception on write operation"), but this time on the line:

object[] currentRowContents = new string[ColumnCount];

I then let it do its thing again ("change type of local variable to string[]...")

...so this changes that line to:

string[] currentRowContents = new string[PLATYPUS_COL_COUNT];

...(IOW, it changes it back to the first version, but with an explicit rather than implicit string array declaration); but a subsequent run of ReSharper will want me to change string[] to var, etc.

like image 397
B. Clay Shannon-B. Crow Raven Avatar asked Dec 27 '22 18:12

B. Clay Shannon-B. Crow Raven


1 Answers

Your code is absolutely perfect while the array is used to retrieve data from it.

Unfortunately, ReSharper is unable to detect if there are writes to that array (Global program verification is unsolved problem in Computer Science at the moment :) ), and if there are assignments to array element, the program will throw exception at run-time if something except string is assigned to.

like image 139
Evgeny Pasynkov Avatar answered Dec 29 '22 09:12

Evgeny Pasynkov