Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 747
myermian Avatar asked Dec 27 '11 22:12

myermian


2 Answers

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();
like image 151
Adam Avatar answered Oct 26 '22 05:10

Adam


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

like image 42
the_joric Avatar answered Oct 26 '22 07:10

the_joric