Link to home
Start Free TrialLog in
Avatar of tommoran
tommoran

asked on

Problem with a date public class

I keep getting an error that I am using an unasigned local variable with the following.  Can anyone tell me what I am missing?

public class IsYear
{
    private bool ValidYear;
      public IsYear(string sYear)
      {
      int I;
      ValidYear = true;
      try
      {
          I = int.Parse(sYear);
      }
      catch
      {
          ValidYear = false;
      }
      if (I < 1000)
      {
          ValidYear = false;
      }
      if (I > 2099)
      {
          ValidYear = false;
      }
      }

      public static implicit operator bool(IsYear id)
      {
          return id.ValidYear;
      }
}

The error, looks like this.

Compiler Error Message: CS0165: Use of unassigned local variable 'I'

Source Error:

 

Line 27:           ValidYear = false;
Line 28:       }
Line 29:       if (I < 1000)
Line 30:       {
Line 31:           ValidYear = false;

Thanks in advance,
Tom
ASKER CERTIFIED SOLUTION
Avatar of PoeticAudio
PoeticAudio

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mikal613
yeah hes right

you have to "USe" all your variables and if its aobject you do

Object Obj = null;
Avatar of PoeticAudio
PoeticAudio

Unfortunately you will not be able to do

int i = null;

because integer is a value type, so you will get a different error. But what Mikal said will work for non value type objects.
i never sadi you could for the int.

I said for objects.

Avatar of tommoran

ASKER

That worked like a champ.  I actually had it set that way previously.  I guess it was deleted by mistake and I just needed another set of eyes to look at it.

Thanks all
good job Poetic :)
I wasn't saying that you were wrong, I was just pointing out why int = null will not work in this case... just in case the author were to try that.
no problem
The problem is that if

I = int.Parse(sYear);

failed you come in the catch

In that case you didn't assign I

a way to solve the problem is too assign I in the catch with a default

I = 0;


or make de declaration

      int I = 0;



public class IsYear
{
    private bool ValidYear;
     public IsYear(string sYear)
     {
      int I;
      ValidYear = true;
      try
      {
          I = int.Parse(sYear);
      }
      catch
      {
          I = 0;
          ValidYear = false;
      }
      if (I < 1000)
      {
          ValidYear = false;
      }
      if (I > 2099)
      {
          ValidYear = false;
      }
     }

      public static implicit operator bool(IsYear id)
      {
          return id.ValidYear;
      }
}