Home > database >  if else statement inside a local variable/class
if else statement inside a local variable/class

Time:06-05

Why cannot I use if else statement inside this local variable account? Inside the "if" I'm planning to enter the code IsActive = "Yes", then inside the "else" IsActive = "No". But the IsActive string that I declared in the class is not appearing/suggesting.

private void btnAdd_Click(object sender, EventArgs e)
{
    UserAccount account = new UserAccount()
    {
        FirstName = txtFirstName.Text,
        LastName = txtLastName.Text,
        Email = txtEmail.Text,
        TeamName = txtTeamName.Text,
        Password = txtPassword.Text,
        // IsActive = "Yes",
        if (chkIsActive.Checked == true)
        {
        }
        else
        {
        }
        UserId = int.Parse(txtUserId.Text)
    };
}

CodePudding user response:

You are trying to use control statement inside the class initializer. You cannot do that.

  1. You can use ternary operator.
UserAccount account = new UserAccount()
{

    FirstName = txtFirstName.Text,
    LastName = txtLastName.Text,
    Email = txtEmail.Text,
    TeamName = txtTeamName.Text,
    Password = txtPassword.Text,
    //IsActive = "Yes",
    IsActive = chkIsActive.Checked ? "Yes" : "No",
    UserId = int.Parse(txtUserId.Text)
};

  1. Don't use boolVariable == true, just use boolean itself. Only exception is a nullable boolean.

CodePudding user response:

You can't use an if else statement inside an object initialization. You can only assign to public writable (that is, properties having a setter) properties there. As suggested in one comment below, starting from C# 9 you can also set init-only properties when using object initialization syntax. These properties can be written only during object construction, once the object construction phase is completed you are not allowed to write the property. Regardless of the C# language version, you can't use any control flow statement in object initialization.

A working version of your code is the following:

    string isActive = chkIsActive.Checked ? "Yes": "No";

    var account = new UserAccount()
    {

        FirstName = txtFirstName.Text,
        LastName = txtLastName.Text,
        Email = txtEmail.Text,
        TeamName = txtTeamName.Text,
        Password = txtPassword.Text,
        IsActive = isActive,
        UserId = int.Parse(txtUserId.Text)
    };

CodePudding user response:

You can do this a few ways, the following is an example of using a ternary condition to set the property value:

private void btnAdd_Click(object sender, EventArgs e)
{

    UserAccount account = new UserAccount()
    {
        FirstName = txtFirstName.Text,
        LastName = txtLastName.Text,
        Email = txtEmail.Text,
        TeamName = txtTeamName.Text,
        Password = txtPassword.Text,
        IsActive = chkIsActive.Checked ? "Yes" : "No",
        UserId = int.Parse(txtUserId.Text)
    };
  • Related