I have the following method defined in a class:
public bool LogOff(string sessionId)
{
int res;
// Some non related code here..
if (res == 1)
{
return true;
}
return false;
}
What's strange to me is that I'm getting a "Local variable might not be initialized before accessing" error from Visual Studio (I do have ReSharper installed) on the IF clause. Why is this the case when "res" is a value type and as such should default to 0? I should point out that if I specifically set the value of res to 0 then it's all OK.
What am I missing here? I thought these are the basics of programming but apparently I'm not familiar with the basics...
The answer to "why does C# work this way" is invariably "because that's what's in the spec." Section 5.3.2 of the C# language specification lists the variables that are not initially assigned:
- Instance variables of initially unassigned struct variables.
- Output parameters, including the this variable of struct instance constructors.
- Local variables, except those declared in a catch clause or a foreach statement.
As to why this is an error, Section 5.3 states
A variable must be definitely assigned at each location where its value is obtained.
If you initialize the value as int res = new int();
, you will get the default value of zero. The more common way is mentioned in other answers, which is to set it to zero explicitly. Relying on default values just makes code less readable with no real advantages.