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?
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
intvariables don’t need initialization because the compiler automatically initializes anintto 0, but if this is taken to a different degree with astringor aDateTime, initialization becomes important in the context of a method.