Home:ALL Converter>How to avoid initialization of these variable?

How to avoid initialization of these variable?

Ask Time:2012-07-12T21:44:53         Author:miri

Json Formatter

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?

Author:miri,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/11453206/how-to-avoid-initialization-of-these-variable
Joel Etherton :

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.\n\nEdit: 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.",
2012-07-12T13:48:32
Raymond Chen :

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).",
2012-07-12T13:49:59
stevethethread :

You can rewrite you method like this\n\npublic int Test(string s) {\n const int mod = 2;\nint start; \nint output = 0;\n\n foreach(int i in s) {\n output = output + (i % mod) + start;\n start++;\n }\n\n return output;\n }\n\n\nIn this case, the start variable does not need to be initialised, and that is true whether declare in inner or outer scope.\n\nHowever, 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.",
2012-07-12T13:50:16
yy