Suspicious warning from Resharper - should I change my code?
Asked Answered
N

2

6

With the following code:

if (lombardiTrophy.Substring(1, 1).Equals('~'))

...I get, "Suspicious comparison: there is no type in the solution which is inherited from both 'string' and 'char'"

Is there a better way to do this that wouldn't cause Resharper to raise its hackles?

Nativeborn answered 6/9, 2012 at 22:47 Comment(5)
.Equals("~") note the double quotesGroove
single quote tries char, double quote forces string, if i remember correctly.Charlsiecharlton
but it compiles fine, and a 1-character string is a char, right?Nativeborn
@ClayShannon No, a 1-character string is still a string, different type.Oviposit
@ClayShannon it compiles fine because it compiles to object.Equals(object), and, because the types are different, the method will always return false. To reiterate, the expression "A".Equals('A') is false. You've no doubt figured that out by now, but nobody else has explicitly called attention to that fact, which is the reason underlying ReSharper's warning.Blaise
M
9

You should heed ReSharper's warning - Substring returns a string, and the single quote notation is a char, so you're comparing two different types. You should compare a char to a char, which you can do like this:

if (lombardiTrophy[1].Equals('~'))

Of course you want to make sure that your string is at least two characters long.

Memberg answered 6/9, 2012 at 22:50 Comment(1)
@Charlsiecharlton The reason he's getting the error is that '~' is a char and Substring returns a string. Since he just needs a character, he should use the Indexer ([]), which returns a char. That way he's comparing char to char and not string to char.Memberg
U
6

Try this:

 if (lombardiTrophy.Substring(1, 1).Contains("~"))

Note the double quotes for string comparison.

Uund answered 6/9, 2012 at 22:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.