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?

2 comments:

Mark Rendle said...

new[] {
ThisCheckBox,
ThatCheckBox,
TheOtherCheckBox }
.FirstOrDefault(cb => cb.Checked);

Rory said...


new[] {
ThisCheckBox,
ThatCheckBox,
TheOtherCheckBox }
.FirstOrDefault(cb => cb.Checked);


This presupposes the sole point of the select, was to return the first checkbox which had been checked.

In reality you'd typically want to do something on the basis of which checkbox had been chosen.

In this case the best the italicised code can do is allow us to store the first checked checkbox in some variable.

Thus:


var FirstChecked = new[] {
ThisCheckBox,
ThatCheckBox,
TheOtherCheckBox }
.FirstOrDefault(cb => cb.Checked);



At this point we're still left trying to write a nasty if {} else structure because we can't switch on FirstChecked because it isn't a constant.