Local Variable Declaration Issue

后端 未结 4 1092
醉梦人生
醉梦人生 2021-01-21 09:26

Im getting the following error:

Cannot use local variable \'dob\' before it is declared

Here is my implementation

pu         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 09:59

    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; } 
    

提交回复
热议问题