That One Dude
That One Dude

Reputation: 31

Else does not work

I am not sure what I am doing wrong! The else command and the bracket above it seem not to act correctly:

public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    if (username_txtb.Text == username && password_txtb.Text == password);
    {
        MessageBox.Show("You are now logged in!");
    }
    else ;
    {
        MessageBox.Show("Sorry, you have used the wrong username and password. Please try again.");
    }
}

Upvotes: 0

Views: 109

Answers (3)

user2864740
user2864740

Reputation: 61965

The presented code results in a syntax error that should read:

Invalid expression term 'else'

The syntax error is caused by the semicolon trailing the if (the semicolon after the else will result in "unexpected behavior" when running the program, and the same principle applies).

if (..);
{
    ..
}
else ..

Is equivalent to

if (..)
    /* empty statement - no code run when if is true! */ ;

/* arbitrary code in a block *not associated* with the `if` */
{
    ..
}

else ..

In this case the "arbitrary code block" ends the if-statement grammar construct.

To fix the syntax error (and the semantic problem), remove the semi-colons after both the if and else statements:

if (..) /* no semicolon */
{
    MessageBox.Show("..");
}
else /* no semicolon */
{
    MessageBox.Show("..");
}

Upvotes: 2

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44448

else ;

should be

else

Remove the semicolon, it will prevent the body from executing.

private void button1_Click(object sender, EventArgs e)
{
    if (username_txtb.Text == username && password_txtb.Text == password) //; - remove
    {
        MessageBox.Show("You are now logged in!");
    }
    else //; - remove
    {
        MessageBox.Show("Sorry, you have used the wrong username and password. Please try again.");
    }

}

Upvotes: 2

BartoszKP
BartoszKP

Reputation: 35901

Note that:

else ;

is equivalent to:

else
{
}

So:

else ;
{
     //some code
}

is equivalent to:

else
{
}
{
    //some code
}

And more clearly, it's equivalent to:

else
{
}

// the conditional clauses are over,
// nothing special here except for an extra scope
// which is a valid construct (even though being useless here)
{
    //some code
}

The second block is not really related to the condition - it just a code block in brackets creating a useless scope, and will be always executed.

The same rules apply after if.

Upvotes: 2

Related Questions