0

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Daniel Cole
  • 49
  • 1
  • 8
  • you can assign null to your variables but you have to change your variables to null-able. https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx – Jugal Panchal Mar 11 '15 at 05:37

2 Answers2

4

Try this

int? mMax = null;
int? mMin = null;
Chris Leyva
  • 3,478
  • 1
  • 26
  • 47
  • Bingo. `int? max;` declares max, but it isn't assigned any value yet - you can't even compare it to `null`. This causes the compiler to tell you it is unassigned. – Conduit Mar 11 '15 at 05:15
  • Thanks! Ended up working. Sorry if its a stupid question but why is it that it would work as a member variable when I didn't set it a value? Are member variables automatically set to null unless otherwise specified? – Daniel Cole Mar 11 '15 at 05:18
  • @DanielCole instance variable will be assigned default value if not initialized. local variables must be assigned before it is used. – Jenish Rabadiya Mar 11 '15 at 05:22
0

you can try this:

int? max = null;
int? min = null;

Why are you getting this compilation error.

it attempts to use the variable a before it is assigned a value. The rules governing definite assignment are defined in here.

Jenish Rabadiya
  • 6,708
  • 6
  • 33
  • 62