Evaluate true in C# using switch

  • Thread starter Thread starter Jim
  • Start date Start date
J

Jim

Hey all, I'm hoping someone may be able to help me. I need to evaluate
some strings to see if their values are what I expect and it doesn't
seem to work. Any help you can provide would be really appreciated.
Here is my non-working syntax:

switch(true)
{
case Header.ParentSectionDisplayName == String.Empty:
MyString = Header.SectionDisplayName;

case Header.ParentSectionDisplayName != String.Empty &
Header.Breadcrumb.ParentSectionCategoryDisplayName ==
String.Empty:
HBXPageName = Header.SectionDisplayName;
}
 
Jim,

You can not do this with C#. You will have to use if statements in
order to branch out this logic.

Hope this helps.
 
You cannot use expression in switch statements, they must be constants.

Use IF block.
 
Your way of writing switch statements looks more like a COBOL style,
which is the reverse of the way C# does it. C# insists on:

switch (expression)
{
case value1:
case value2:
...
}

you have the value in the "switch" and the expressions in the "case"s.

As well, C# insists that the expression and the values be simple types
like integers and enums. Strings, floating point values, decimal
values, and types you create yourself aren't allowed.

To do what you want, you need to say:

if (Header.ParentSectionDisplayNam­e == String.Empty)
{
MyString = Header.SectionDisplayName;
}
else if (Header.ParentSectionDisplayNam­e != String.Empty &&
Header.Breadcrumb.ParentSectio­nCategoryDisplayName ==
String.Empty)
{
HBXPageName = Header.SectionDisplayName;
}

etc.

(Also take care to use && in boolean tests rather than &.)
 
Bruce said:
Your way of writing switch statements looks more like a COBOL style

Just an FYI that isn't really relevant. You can also write that style of
switch statement in VB(6 and .NET).

Select Case True
Case Header.ParentSectionDisplayName = "":
MyString = Header.SectionDisplayName
Case Header.ParentSectionDisplayName <> "" And
Header.Breadcrumb.ParentSectionCategoryDisplayName = "":
HBXPageName = Header.SectionDisplayName
End Select
 
Back
Top