Is there any difference in how you read a value — IE: store cell value in variable vs get from datagrid

OK, so lets say I want to read a value out of a DataGrid. I might write something like:

if(myDGV.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToLower() == "myvalue") { DoSomethingAwesome(); } else if(myDGV.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToLower() == "myothervalue") { DoSomethingAwesome(); } 

That's really long winded… so I usually just get that value into a string.

string myCellValue = myDGV.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToLower(); if(myCellValue == "myvalue") { DoSomethingAwesome(); } else if(myCellValue == "myothervalue") { DoSomethingAwesome(); } 

So the question is, is there a difference in those two lines of code? Besides readability, does it take the application longer to read the value of the cell — after all, it does have to read out the value of e.RowIndex and e.ColumnIndex and then it has to read out the value of the cell

Is the Compiler reading RowIndex, ColumnIndex, CellValue for the first if statement, then jumping to the else if and reReading rowIndex, ColumnIndex, and CellValue again?

Or is the compiler smart enough to realize that the IF and ELSE IF both read the same value — so it only reads the value one, and compares it twice?

Because if it's the latter, I feel like the long-winded route is more effeciant since it has the same amount of variable reads and doesn't require memory for an extra string variable.

NOTE: I prefer readability so I always declare a string, I was just curious how the application handled all of this in the background. You know, curiosity, knowledge is power, that sort of thing.

by irtehawesome via /r/csharp

Leave a Reply