Home > database >  Question about else statement following if-else
Question about else statement following if-else

Time:08-16

I'm brushing up on some C# and had a question that seemed dumb. In C# (and probably most languages), can you put an else statement inside an if-else statement?

e.g.

if (clause) {
  execute code
}
else if (clause) {
  execute code
     else {
       execute code
  }
}

CodePudding user response:

This should be erroneous. You probably want something like this instead:

if (clause)
{
    // do something
}
else
{
    if (anotherClause)
    {
        // do something
    }
    else
    {
        // do something
    }
}

I assume you are new to programming, so I can talk a little bit about if else statements.

else does not make any sense when you don't have an if before it.

For example, This statement makes sense:

IF you are 21 or older, you can drink. ELSE, you cannot drink.

While this does not:

ELSE, you cannot drink

Hopefully my answer helps

CodePudding user response:

That code wouldn't work because you need an if for there to be an else. If you want to do an additional check for something within the else if, you need to add an if first, like this:

if (clause)
{
  execute code
}
else if (clause)
{
  execute code
    if (clause)
    {
       execute code
    } 
    else
    {
       execute code
    }
}

CodePudding user response:

it is not possible but you can do something like that instead :

if(condition)
{
  //code that get executed after cheking the condition 
}
else if(another condition)
{
  // code that get executed after checking the second condition
}
else
{
 // code get executed if the first and the second condition are not true
}
  •  Tags:  
  • c#
  • Related