If I write the following code :
if(string.IsNullOrEmpy(myObj.GetString()))
{
var myString = myObj.GetString() + myObj.GetString();
}
My function GetString() will be called 3 times, then it can execute some complex code 3times. Is there a simpler way than :
var firstString = myObj.GetString();
if(!string.IsNullOrEmpy(firstString))
{
var myString = firstString + firstString;
}
to have only one execution of the code in GetString() ?
You COULD make it more complex and have an IsChanged bool value, and if anything in the object changes set IsChanged to true and then rebuild the string, else return the last string built, but then you’d need to add synchronization and it probably wouldn’t be worth the cost.
So, the long and the short is that the 2nd case is generally the best case. It’s simple and straightforward and efficient.
UPDATE: It’s hard to tell what the update scenario is here. So let’s look at several.
1). If you are only updating the string on demand from the application, and that string is created using some complex method, just have a new update method and then return the current string as a property. Then, you can just query the MyString property and it will be a simple return.
2). Or, if it’s just a simple string with no complex logic, you could have the application responsible for creating and assigning it:
But as I said, that’s only if the string representation is independent from the state of the object.
3). If it’s based on the state of the object and changes when the object state changes, you could let the string be re-created whenever something changes:
But once again, you’d probably want to synchronize this if it’s multi-threaded use.
BUT This is all IF you want to cache the value so it’s not rebuilt each time as a responsibility of the class itself.
Truly, your simplest and best bet is just to use your second method, and if you are using it several times in one method just set to a temporary variable and use that.