Embedded statement cannot be a declaration or labeled statement

后端 未结 2 769
悲哀的现实
悲哀的现实 2020-12-05 09:25

I am trying to create a user using claim identity asp.net I get this error while creating claims identity user.

  ApplicationUser user = new ApplicationUser         


        
相关标签:
2条回答
  • 2020-12-05 09:41

    You have a statement (if or while, for example), right before the code you posted, without curly braces.

    For example:

    if (somethingIsTrue) 
    {    
       var user= new ApplicationUser { 
           UserName = model.myUser.Email,
           Email = model.myUser.Email ,
       };
    }
    

    is correct, but the code below:

    if (somethingIsTrue) 
       var user = new ApplicationUser { 
          UserName = model.myUser.Email,
          Email = model.myUser.Email ,
       };
    

    will result in CS1023: Embedded statement cannot be a declaration or labeled statement.

    UPDATE

    The reason, according to @codefrenzy, is that the newly declared variable will immediately go out of scope, unless it is enclosed in a block statement, where it can be accessed from.

    The compilation will pass in the following cases though.

    If you only initialize a new instance of a type, without declaring a new variable:

    if (somethingIsTrue) 
       new ApplicationUser { 
           UserName = model.myUser.Email,
           Email = model.myUser.Email ,
       };
    

    or if you assign a value to an existing variable:

    ApplicationUser user;
    
    if (somethingIsTrue) 
       user = new ApplicationUser { 
           UserName = model.myUser.Email,
           Email = model.myUser.Email ,
       };
    
    0 讨论(0)
  • 2020-12-05 10:01

    I just had this error, and the fix was to add a curly brace to the if immediately preceding my code, and then remove it again. Visual Studio facepalm OTD.

    0 讨论(0)
提交回复
热议问题