Char.Equals vs Object.Equals -- ReSharper suggests that I should use Object.Equals. Should I?
Asked Answered
E

2

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?

Encomiastic answered 27/12, 2011 at 22:5 Comment(6)
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)Schoolmaster
What's the actual line of code? Does ReSharper give any reasoning for its suggestion?Billposter
my resharper does not suggest that :)Lathing
@Kyralessa: I added some code.Encomiastic
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.Loveinidleness
Consider the fact that your code works as expected if you replace Char.Equals with Boolean.Equals, 'System.Console.Equals, Uri.Equal`, etc.Breunig
L
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();
Lincolnlincolnshire answered 27/12, 2011 at 22:22 Comment(2)
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?Polis
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...Lincolnlincolnshire
L
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

Lathing answered 27/12, 2011 at 22:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.