Thursday 23 December 2010

switch vs Select Case

I knew if I looked long enough, I'd find something you can do in VB.NET that you can't do in C#. And I think I just found it.


Consider this bit of markup:
Why is it not possible to use an existing approved supplier?
<asp:radiobutton id="ClientNominatedRadioButton" runat="server" text="Nominated/named by client" GroupName="NewSupplierReasonRadioButtonGroup" />
<asp:radiobutton id="AlreadyOnSiteRadioButton" runat="server" text="Already on site" GroupName="NewSupplierReasonRadioButtonGroup" />
<asp:radiobutton id="NewLocationRadioButton" text="New location and no existing supplier" runat="server" GroupName="NewSupplierReasonRadioButtonGroup" />
<asp:radiobutton id="OtherRadiobutton" runat="server" text="Other (please state)" GroupName="NewSupplierReasonRadioButtonGroup" runat="server" />

At some point, I'll want to examine this set of radio buttons to deduce which one is selected. In VB.NET, I would normally do this with a Select Case construct, viz.
Select Case True

    Case ClientNominatedRadioButton.Checked

    Case AlreadyOnSiteRadioButton.Checked

    Case NewLocationRadioButton.Checked

    Case OtherRadiobutton.Checked

End Select
which I always think is a more elegant construct than a thousand 'if...then...else if...then..else if' blocks.

But it seems this construct is not available in C# - here's a screenshot from Visual Studio:


 
 
 
 
 
 
 
 
 
The tooltip for the red squiggly reads 'Code is unreachable. A constant value is expected'.
 
All of which leaves me slightly confused. If they compile down to the same bytecode then why does this approach work in only one language? And is there a more elegant way to determine the selected radiobutton than the aforementioned 'if...then' block?