Reputation: 2715
I have written a method with the idea of keeping a certain variable in memory in order to optimize the program. The issue i'm having is that in the variable previousSearchInfoForSavings
seems to always be the same as searchInfo
even though it shouldn't be as it is only assigned in certain places.
The idea is that if you pass in the same searchInfo
array it will recognise that it is the same as previousSearchInfoForSavings
and not run the ClearPageNavigation.main
method.
However this does not seem to be the case. If different values are passed in for searchInfo
it doesn't seem to matter and and previousSearchInfoForSavings
seems to automatically update to these values.
For example:
If I pass in {"X","Y","Z"} in as searchInfo
the first time previousSearchInfoForSavings
is null so it will enter that if statement. This is fine. The next time if I pass in {"A","B","C"} at the beginning (where the comments are) these arrays are already equal. This should not be the case.
My code:
private static TableRow[] TRforSavings = null;
private static string[] previousSearchInfoForSavings = null;
public static bool[] main(
string[] searchInfo,
string[] compareInfo,
string ClearFinancesTestPageURL
) {
if (searchInfo[1] == "Savings") {
//searchInfo == previousSearchInfoForSavings here
bool[] results;
if (previousSearchInfoForSavings == null) {
previousSearchInfoForSavings = searchInfo;
TableRow[] TR = ClearPageNavigation.main(
ClearFinancesTestPageURL,
searchInfo[0],
searchInfo[1],
searchInfo[2],
searchInfo[3]
);
results = CompareSavings.main(TR, compareInfo);
TRforSavings = TR;
} else {
if (ArraysEqual(previousSearchInfoForSavings, searchInfo)) {
results = CompareSavings.main(TRforSavings, compareInfo);
} else {
TableRow[] TR = ClearPageNavigation.main(
ClearFinancesTestPageURL,
searchInfo[0],
searchInfo[1],
searchInfo[2],
searchInfo[3]
);
results = CompareSavings.main(TR, compareInfo);
TRforSavings = TR;
previousSearchInfoForSavings = searchInfo;
}
}
//searchInfo == previousSearchInfoForSavings here
return results;
}
}
Any ideas?
Upvotes: 0
Views: 137
Reputation: 6016
This problem happens because you are assigning previousSearchInfoForSavings = searchInfo and thus copying searchInfo's reference in your local variable. And I suspect that you are sending the same searchInfo into your main method with changed values and that's why array elements change in both instances. To avoid this you have to copy searchInfo elements into previousSearchInfoForSavings instead of assigning.
Upvotes: 0
Reputation: 1031
The problem is that you're using reference types, and you should be cloning "searchInfo" instead of setting "previousSearchInfoForSavings" to be equal to it. So instead of:
previousSearchInfoForSavings = searchInfo;
You should be doing something like:
previousSearchInfoForSavings = (string[])searchInfo.Clone();
Upvotes: 3