8

Basically, I'm wondering if I should listen to ReSharper in this instance...

You'd figure that comparing to characters one should use Char.Equals(char) since it avoids unboxing, but Resharper suggests using Object.Equals(obj). Maybe I'm missing something here?


private const DEFAULT_CHAR = '#';

// DependencyProperty backing
public Char SpecialChar
{
    get { return (Char)GetValue(SpecialCharProperty); }
}

// ReSharper - Access to a static member of a type via a derived type.
if (Char.Equals(control.SpecialChar, DEFAULT_CHAR)) { ... }

I'm guessing it's because there is a DependencyProperty backing?

myermian
  • 31,823
  • 24
  • 123
  • 215
  • The Equals from my understanding compares like things or unlike for example you would not say ObjectA == ObjectB you would check that using the ObjectA.Equals(ObjectB) – MethodMan Dec 27 '11 at 22:08
  • 2
    What's the actual line of code? Does ReSharper give any reasoning for its suggestion? – Ryan Lundy Dec 27 '11 at 22:09
  • 1
    my resharper does not suggest that :) – the_joric Dec 27 '11 at 22:09
  • @Kyralessa: I added some code. – myermian Dec 27 '11 at 22:16
  • 3
    It's not because it's a dependency property, it's because you're calling a static method from `System.Object` via a descendant class (`System.Char`). ReSharper's warning message ("Access to a static member of a type via a derived type") makes that fairly clear, I think. – Joe White Dec 27 '11 at 22:28
  • 1
    Consider the fact that your code works as expected if you replace `Char.Equals` with `Boolean.Equals`, 'System.Console.Equals`, `Uri.Equal`, etc. – Austin Salonen Dec 27 '11 at 22:37

2 Answers2

13

It is impossible to override static members - Object.Equals() is a static member, and Char cannot override it, even though you can call it on the Char type (the params are still of type Object)

Therefore, it makes no difference whether you call

Object.Equals(object yourChar, object anotherChar) 

or

Char.Equals(object yourChar, object anotherChar)

since boxing will occur in either case.

To avoid this, use the instance method, which is overridden in Char:

if (yourChar.Equals(anotherChar)) doSomething();
Adam
  • 15,537
  • 2
  • 42
  • 63
  • I would expect that resharper would suggest me to use the overridden instance version of `Equals`. Is this a bug or is it not possible to detect if there's an instance version of a static member via reflection? – Tim Schmelter Dec 27 '11 at 22:30
  • see @Joe White's comment on the question - ReSharper is quite helpful, but it can't do *everything* for you. In fact, when I type `Char` and then `.Equ`, ReSharper seems to have overridden IntelliSense to **hide** `Object.Equals`... – Adam Dec 27 '11 at 22:32
5

Char.Equals(control.SpecialChar, DEFAULT_CHAR) is a call to Object.Equals(object, object), so resharper is correct here.

I would suggest to use control.SpecialChar.Equals(DEFAULT_CHAR) or just DEFAULT_CHAR == control.SpecialChar

the_joric
  • 11,986
  • 6
  • 36
  • 57