Problem with local variable

Im getting the following error:

You cannot use the local variable 'dob' before it is declared

Here is my implementation

public class Person
    {
        ...
        public string dob { get; set; }
        ...

       public int getAge()
       {
                DateTime origin = DateTime.Parse(dob);
                return DateTime.Today.Year - origin.Year;
        }

        public string getFormattedDoB()
        {
                DateTime origin = DateTime.Parse(dob);
                string dob = origin.ToString("d");
                return dob;
        }
    }

I'm not sure what to do with this, because he complains about using dob in getFormattedDoB(), but not in getAge(), which precedes it. If anyone could shed light on this, that would be great

+3
source share
4 answers

You specified a local variable in getFormattedDoB called dob. The compiler cannot tell the difference between this and the dob member. Try adding "this", where you mean a member variable, not a local one:

DateTime origin = DateTime.Parse(this.dob);

Even better, do not use the same name for a local variable.

: -, . "", .

+9

, dob s- . (string dob = ...) - ( { }). , :

DateTime origin = DateTime.Parse(dob);

dob , () dob.

, . #

public String DateOfBirth { get; set; } 
//(assuming that is what DOB stands for)

public DateTime DateOfBirth { get; set; } 
+4

You reused the name of the dob variable getFormattedDoBas a local string, which confuses the compiler. There are 2 possible solutions:

  • Rename the local dob to getFormattedDoB (which you really should do, because it's good practice).
  • Use this.dob on the next line to specify a class level variable (which you probably should also do, because it is also good practice:

    DateTime origin = DateTime.Parse (this.dob);

0
source

You update dob in

string dob = origin.ToString("d"); 

he should be

 dob = origin.ToString("d"); 
0
source

All Articles