The scope of local variables should always be as minimal as possible. So, I would declare the variable precisely there where it is used even if I have to re-declare it in multiple places within the same method. As a matter of fact, I would declare it precisely where it is used even if there was no if
condition. Many people do not know it, but you can start a new scope with curly brackets anywhere you want within a method, even if you do not have a control statement to put it under. For example:
//some code
//comment explaining what the following does:
{
string emailAddress = Foo();
EmailMessage.To = emailAddress;
}
//more code
//comment explaining what the following does:
{
string emailAddress = Boo();
SomeOtherEmailMessage.From = emailAddress;
}
//yet more code
One more note: I see that when your colleague declared the email address variable he assigned string.Empty
to it, and then further down he re-assigned a meaningful value to it prior to using it. Some people believe that when declaring a local variable you should always initialize it with some initial value, and they follow this rule in an almost superstitious fashion. This is wrong. It may have been advisable back in the times when all we had was some primitive and crude C compilers, but not anymore. Modern compilers of C, C++, C# and Java are quite good at warning you if a variable might be read before it has been initialized. So, by pre-initializing the variable at declaration time with a value which is by definition meaningless, (since a meaningful value is not yet known at that time,) you are circumventing the safety checks of your compiler, and you are actually opening up the possibility of error: if you forget to assign a proper value to your variable further down before you actually make use of it, the compiler will not warn you, because as far as the compiler knows, the variable has already been initialized at declaration time.
Furthermore, even if the compiler was incapable of warning about uninitialized values, you would still have to wonder which outcome is better for a program with an uninitialized variable bug: to fail with a null pointer exception the first time it is used, or to appear to work but never send any messages to anyone.
In any case, you should not really have to worry about the above note, because if you follow the rule which says that the scope of local variables should always be as minimal as possible, you will always be initializing your local variables with meaningful values precisely at the moment that you are declaring them.