Reputation: 1691
I was reading on the net (http://www.codinghorror.com/blog/2005/07/for-best-results-dont-initialize-variables.html) that we should not initialize variables.
Somehow I dont get it. Often I just cannot avoid that. Lets look on a simple example:
public int test(string s)
{
int start = 0;
int mod = 2;
int output = 0;
foreach (int i in s)
{
output = output + (i % mod) + start;
start++;
}
return output;
}
Ok its maybe a nonsense :-) But the question is: can I avoid the initialization? Maybe its not possible for mod, because mod have to be 2 from the beginning and it will stay 2. But how about start and output? I just cannot write int start
because thats always Error Use of unassigned local variable
. Maybe int start = null
would be better, but in this case its not gonna work too. So how to avoid this stuff?
Upvotes: 1
Views: 736
Reputation: 37543
You've misread his article. In his article he is specifically talking about initialization of variables with respect to classes. In the case you've put forth, your variables should be initialized before they can be used because they'll be immediately used.
Edit: Yes, in this specific case the int
variables don't need initialization because the compiler automatically initializes an int
to 0, but if this is taken to a different degree with a string
or a DateTime
, initialization becomes important in the context of a method.
Upvotes: 5
Reputation: 1419
The article is talking about not to initialize variables with default values. For example,
int x = 0;
is not good. Also, you should initialize (and declare) the variable just before it's usage is a clean code.
Initialization in constructor is not just before the usage.
Upvotes: -2
Reputation: 2524
You can rewrite you method like this
public int Test(string s) {
const int mod = 2;
int start;
int output = 0;
foreach(int i in s) {
output = output + (i % mod) + start;
start++;
}
return output;
}
In this case, the start variable does not need to be initialised, and that is true whether declare in inner or outer scope.
However, the output variable does need initialisation due to the fact that it will be returned by the method, and is possible that if the loop never runs, the variable would never be initialised.
Upvotes: 1
Reputation: 45172
You misread the article. The article is talking about member variables (which are automatically initialized to default values and therefore do not require explicit initialization), but you are trying to apply the rule to local variables (which are not automatically initialized and therefore require explicit initialization).
Upvotes: 5