Probably a pretty quick fix, but I'm working on a project in Visual Studio in which the program reads in a text file of numbers and then calculates certain statistics for them.
I originally had initiated two member variables to represent minimum and maximum.
private int? mMax;
private int? mMin;
The method would then compare the current number in the file to those member variables, and change accordingly. However, I needed to be able to check if these were null. I could not simply set them to a default 0 because negative numbers are also involved.
This was my implementation, with
int a = //current number in the file
if (mMax == null && mMin == null)
{
mMax = a;
mMin = a;
}
else
{
//compare and assign min & max accordingly
}
This was all fine and dandy, until I realized that the enduser would be able to run another file through the method body after they had finished the first. This means that the member variables would already be set from the first run of the method.
So, instead of making min and max member variables, I made them simply variables within the method's scope.
However, when running this code:
int? max;
int? min;
if (max == null && min == null)
{
...
}
I receive the error "Use of unassigned local variable 'max' and 'min' ".
Can anybody tell me why this is happening? I intended for these variables to be unassigned, but obviously there is something wrong with me doing this. Why is it that it worked completely fine as member variables but not local variables?
Try this
int? mMax = null;
int? mMin = null;