Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

c# - Embedded statement cannot be a declaration or labeled statement

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 { 
                        EmailConfirmed = true, 
                        UserName = model.myUser.Email,
                        Email = model.myUser.Email ,
                        PhoneNumber = model.myUser.PhoneNumber,
                        PhoneNumberConfirmed = true,
                        UserImagePath = model.myUser.UserImagePath,
                        FirstName= model.myUser.FirstName,
                        LastName = model.myUser.LastName,
                        DateOfBirth = model.myUser.DateOfBirth,
                        Culture = model.myUser.Culture,
                        Role = model.myUser.Role
                    };

but when the code was

var user= new ApplicationUser { 

                            UserName = model.myUser.Email,
                            Email = model.myUser.Email ,

                        };

it worked perfectly, so i want to know what is wrong

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...