0

I have read many posts on Stackoverflow on the subject of 'if statements vs case statements' though I haven't yet come across a post that outlines the advantages of if statements over case statements.

Reading previous posts I have learnt that case statements can be more efficient (in terms of speed) and they have better readability. But why would one use if statements over case statements?

Thanks.

Tahmid
  • 185
  • 1
  • 4
  • 20
  • 1
    I use case with a distinct set of choices, and if with complex logic – Jeremy Mar 06 '15 at 01:43
  • Both statements are efficient. You should use the one that best suits your purpose. – Blackwood Mar 06 '15 at 01:46
  • @Jeremy, So something like `If txtPassword.Text = "test" And txtUsername.Text = "test" Then Form1.Show() Else Messagebox.Show("You have entered the name username/password combo") End If` is best suited to an if statement? Do you classify this as 'complex logic'? – Tahmid Mar 06 '15 at 01:50
  • possible duplicate of [Case vs If Else If: Which is more efficient?](http://stackoverflow.com/questions/2158759/case-vs-if-else-if-which-is-more-efficient) – Trevor Mar 06 '15 at 02:06
  • [Related](http://stackoverflow.com/questions/767821/is-else-if-faster-than-switch-case) and [Related](http://stackoverflow.com/questions/395618/is-there-any-significant-difference-between-using-if-else-and-switch-case-in-c) . These should be enough to answer your question – Baby Mar 06 '15 at 02:12
  • Yes thats what im talking about – Jeremy Mar 06 '15 at 03:01

1 Answers1

1

A case statement analyses a specific input, an If statement could be something like:

If left("Text",1) = "T" then
    BlahBlah
elseif left("SomeOtherText",2) = "So" then
    Other Blah Blah
elseif X+Y = 3 then
    Something else
end if

If I was testing the same thing I would use a case:

Select Case X+Y
Case 3
    Something
Case 5
    Something Else
Case Else
    Blah Blah
End Select

I use them both in different circumstances

Dan Donoghue
  • 6,056
  • 2
  • 18
  • 36