Comparing string values, weird problem

R

ryanm

I have this function:

private void ParseCommands(String cmd){
switch(cmd)
{
case "!rpt":
Report();
break;
// other cases removed for brevity
default:
Console.WriteLine(cmd);
break;
}
}

...as a member of a class. The class wants to pass a string that may be
text for display, or it may be a command being issued. The problem is that
even if the value being passed to the function is "!rpt", the "!rpt" case
never executes, it always goes to default. Now, the docs say that == is a
value comparison for strings (rather than a reference comparison), and that
the switch expression is evaluated as == to the case value, but it never
returns true. Am I doing something obvious wrong and I just don't see it, or
do I have to do it another way? I tried comparing the values with Compare
and CompareTo, but neither ever returned 0 (equal) for me.

What am I missing?

ryanm
 
M

Morten Wennevik

Hi ryanm,

Are you sure you are passing "!rpt" and not " !rpt", "!rpt " or similar?
 
J

Jon Skeet [C# MVP]

ryanm said:
private void ParseCommands(String cmd){
switch(cmd)
{
case "!rpt":
Report();
break;
// other cases removed for brevity
default:
Console.WriteLine(cmd);
break;
}
}

...as a member of a class. The class wants to pass a string that may be
text for display, or it may be a command being issued. The problem is that
even if the value being passed to the function is "!rpt", the "!rpt" case
never executes, it always goes to default. Now, the docs say that == is a
value comparison for strings (rather than a reference comparison), and that
the switch expression is evaluated as == to the case value, but it never
returns true. Am I doing something obvious wrong and I just don't see it, or
do I have to do it another way? I tried comparing the values with Compare
and CompareTo, but neither ever returned 0 (equal) for me.

What am I missing?

Do you have a short but complete example which exhibits the problem? If
comparing the values with Compare and CompareTo aren't returning 0,
then your string is not "!rpt" even if it looks like it is. I suggest
you dump the contents, like this:

for (int i=0; i < cmd.Length; i++)
{
Console.WriteLine ("{0} {1}", i, (int)cmd);
}

Let us know what you find out...
 
R

ryanm

Jon Skeet said:
for (int i=0; i < cmd.Length; i++)
{
Console.WriteLine ("{0} {1}", i, (int)cmd);
}

Let us know what you find out...

Thanks, all three of you, for the quick response. Turns out there was a
carriage return and line feed at the end of the string, because it's console
input. Changing the switch expression to cmd.Trim() fixed it. Sometimes you
look at something too long and fail to see the obvious...

ryanm
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top