Reputation: 47763
I'm wondering if this is good, bad?
SelectRecipientResponse user = SomeUtil.SelectRecipient(p.Email, p.ListID.ToString());
bool userIsInList = user.ExistsInList;
bool userIsOptedOut = user.IsOptedOut;
user = null;
user = SomeUtil.SelectRecipient(p.Email, _masterSuppressionListID);
bool userIsInSupressionList = user.ExistsInList;
so I'm using one instance of user to check to see if they are in 2 lists. Lists I am checking are over a 3rd party API. I want to do one check, null out that object and reuse it again.
Does this seem typical? I'm just trying to code this smartly so wanted to see what one thinks about this technique above.
Upvotes: 0
Views: 2522
Reputation: 55122
It's completely acceptable to re-assign variables, though there is absolutely no legitimate reason to assign null
to the variable, then assign it to something else.
In terms of readability, when I am re-using local variables, I don't generally assign it on the first declaration.
I'll typically write:
SqlParameter param;
param = new SqlParameter(...);
param.Value = "";
... // and again
param = new SqlParameter(...);
param.Value = "";
In this way, it's kind of clear that it's being re-used (or at least re-assigned). Works for me, anyway, and it means that I can happily re-order things (if it becomes relevant) without too much trouble.
Upvotes: 0
Reputation: 24378
You're asking for trouble when some other developer comes back in a year and starts working with user further down in the method not noticing that you overwrote it with a second assignment. Name your variable what it is. This would probably qualify as unnecessary premature optimization.
Upvotes: 1
Reputation: 882171
Actually, you're using the same variable, i.e. the name user
, to refer (in separate zones of your code) to (possibly-)separate instances of SelectRecipientResponse
, since each call to SelectRecipient
is (or may well be) returning a distinct one. No big problem with that. And no need to set user
explicitly to null
before reassigning it, either.
Upvotes: 4
Reputation: 351566
This is fine because you aren't reusing the object, you are simply reusing the local variable that holds the reference to the object.
That being said, I personally feel that it would be better to simply create a second variable to hold the second reference as I find that more readable.
Upvotes: 6