DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

# Thread: If Statement with Elseif

1. Banned
Join Date
Nov 2004
Posts
293

## If Statement with Elseif

I want to create an if statement like the following

If x=y then z=1
Elseif x=a then z=2
Elseif x=b then z=3
Elseif x=c then z=4
Else z=5
End if

however I'm getting an error stating "Else without if" and highlighting the first Elseif in the sequence. Their must be a way of keeping the Elseif and then statements on the same line as above, does anyone know how?

2. Senior Member
Join Date
Nov 2003
Location
Portland, OR
Posts
8,387
This is as close as I can get. There has to be a carriage return after the first "Then":
Code:
```If x = y Then
z = 1
ElseIf x = a Then: z = 2
ElseIf x = b Then: z = 3
ElseIf x = c Then: z = 4
Else: z = 5
End If```
You might also consider a Select...Case block:
Code:
```Select Case x
Case Is = y: z = 1
Case Is = a: z = 2
Case Is = b: z = 3
Case Is = c: z = 4
Case Else: z = 5
End Select```

3. Banned
Join Date
Nov 2004
Posts
293

## if vs Case

why would the case be perfered over the if, is it faster or somthing ?

4. It is easier to read and understand.

5. Registered User
Join Date
Mar 2008
Location
Lancashire, UK
Posts
156
I think Select Case is also slighty quicker.
But maybe it depends what you're comparing.

With Select Case, you only query the value you're comparing once, so if it's a property of an object, it's more efficient. (You don't repeatadly ask the object what a property's value is)

6. I suspect you are correct about the speed, but, given the speed of today's computers, the extra you pick would probably be almost moot.

7. As was suggested earlier, readability is the key (along with correct syntax ;-)

Try :-
Code:
```If x = y Then
z = 1
ElseIf x = a Then
z = 2
ElseIf x = b Then
z = 3
ElseIf x = c Then
z = 4
Else
z = 5
End If```
For correct syntax see :-
http://msdn.microsoft.com/en-us/libr...bs(VS.80).aspx

The question of whether or not to use Select Case instead sometimes is not even a consideration. OK if each of the 'elseif's is comparing to the same thing (in your case a value of 'z'). However, 'elseif' can be used with different 'evaluations' that you might want to use in a particular order - e.g. if a=b then whatever elseif c=d then whateverelse else somethingelse endif

Greg

P.S. Not sure that speed is really an issue - comparing 5 things? - unless you are looping through 10**n where 'n' is a significant number. If ultimately you are relying on a user at the keyboard or mouse, then ....
Last edited by gupex; 07-17-2008 at 07:32 AM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise