I have been looking through some code on an open source project recently and found many occurrences of this kind of code:
class SomeClass
{
private int SomeNumber = 42;
public ReturnValue UseSomeNumber(...)
{
int someNumberCopy = this.SomeNumber;
if (someNumberCopy > ...)
{
// ... do some work with someNumberCopy
}
else
{
// ... do something else with someNumberCopy
}
}
}
Is there any real benefit to making a copy of the instance variable?
No unless you don’t want to change the value of SomeNumber and you intend on updating someNumberCopy. Like if you were going to loop the number of times and were going to decrement someNumberCopy down to zero to keep track of the count.
I suppose copying the variable like that could protect you from some outside function altering SomeNumber and changing it without your knowledge while performing an operation. I could potentially see this if the class was supposed to be used in a multi-threaded application. Maybe not he way I would go about it, but that could have been the author’s intent.