I just started using C# and I've got a couple of issues. Is there any way to code the C# equivalent of the VB.NET Select statement like the following?
Select Object.Name.ToString()
Case "Name1"
'Do something
Case "Name2"
'Do something else
Case Else
'Do the default action
End Select
Any help would be greatly appreciated.
Thanks for the input so far now what about if I hook several controls to one event handler as in the following and I want to perform a slightly different action for each control:
Private Sub Button_Click(sender as Object, e as EventArgs) _
Handles button1.Click, Button2.Click
'do a general activity
Select CType(sender, Button).Name
Case button1.Name
'do something
Case button2.Name
'do something else
Case Else
'do the defalut action
End Select
End Sub
Is there any way of doing the above select statement in C# without having to use nested ifs?
With C# 7, switch has been significantly enhanced, and it's now possible to apply more conditions within cases, although it's still not as "clean" as the VB version. E.g. you could do something like:
Taken from / References:
You'd be looking for the switch statement...
Note that the breaks are import, otherwise the program will drop through your cases. You should be able to find this on almost any C# introduction...
Use a
switch
statement.And don't forget that there is a free online conversion tool that allows you to convert VB.net to C# and viceversa.
I have come to find over time that some VB.NET
Select...Case
constructs do not apply in C# and the only way around is to write a lot of ifs.For instance, in VB.NET, you can write:
But there is no
switch
construct in C# that allows you to do something of this sort. You'll have to code in roundabout like so:Or if you happen to be working with
Double
or any type which is made up of continuous instead of discrete values, you'll have to useif
s to get the required action.Reason? C#'s
switch
requires constants for the variouscase
s. This is different from VB.NET'sSelect Case
which allows writing ranges.