CStreel
CStreel

Reputation: 2642

Local Variable Declaration Issue

Im getting the following error:

Cannot use 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 am not sure what to make of this because it is complaining about it's use of dob in getFormattedDoB() but not in getAge() which comes before it. If anyone could shed some light on this that would be great

Upvotes: 3

Views: 14993

Answers (4)

Chris Shain
Chris Shain

Reputation: 51329

The problem is that you have two dobs- the property and the local variable. The scope of a variable declaration (string dob = ...) is the whole block (everything between the { and }). Therefore the compiler thinks that on the line:

DateTime origin = DateTime.Parse(dob);

you are using the dob variable before it is declared, when (we assume) you really meant the dob property.

As others have mentioned, you should rename the property. The standard naming convention in C# would be

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

or better yet

public DateTime DateOfBirth { get; set; } 

Upvotes: 4

Krishnanunni Jeevan
Krishnanunni Jeevan

Reputation: 1759

You are redeclaring dob in

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

it should be

 dob = origin.ToString("d"); 

Upvotes: 0

Steve Danner
Steve Danner

Reputation: 22158

You have reused the variable name "dob" in getFormattedDoB as a local string, which is confusing the compiler. There are 2 possible solutions:

  1. Rename the local dob in getFormattedDoB (which you really should do because it's good practice).
  2. Use this.dob in the following line to specify the class level variable (which you should probably also do because it's also good practice:

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

Upvotes: 0

Matt Burland
Matt Burland

Reputation: 45135

You've declared a local variable in getFormattedDoB called dob. The compiler can't tell the difference between that and the member dob. Try adding "this" where you mean the member variable rather than the local:

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

Better still, don't use the same name for the local variable.

Edit: Unless you did actually intended to set the member variable and not create a new one. In which case remove the "string" as Andrew suggested.

Upvotes: 10

Related Questions