user1675891
user1675891

Reputation:

Should I compare integers using the operator or a method?

I'm refactoring my clients code written by an unspecified coder. It looks like this.

int i = ...;
if (i.Equals(123));

I'm very tempted to change it to the usual, namely:

int i = ...;
if (i == 123);

but I'm cautious not to cause any damage. Those calls are equivalent, aren't they? And by any measures, the operator style can't be slower but is definitely more surprising and less readable, right?

Upvotes: 2

Views: 67

Answers (3)

Konrad Viltersten
Konrad Viltersten

Reputation: 39108

Since you're declaring the variable as int, it's a value type and it's recommended to go with the operator style. The method style is to be applied on object typed variables.

You can compare value types and object types.

Upvotes: 0

Chris Gessler
Chris Gessler

Reputation: 23113

When should I use == and when should I use Equals?

Something I didn't know either :)

Value types do not provide an overload for == by default. However, most of the value types provided by the framework provide their own overload. The default implementation of Equals for a value type is provided by ValueType, and uses reflection to make the comparison, which makes it significantly slower than a type-specific implementation normally would be. This implementation also calls Equals on pairs of references within the two values being compared.

Additionally, I use == on strings to avoid the null check.

if(myString == "something")

vs

if(myString != null && myString.Equals("something"))

Upvotes: 1

Habib
Habib

Reputation: 223247

For value types use == operator, since Equals is usually useful with reference types. Since int is a value type it is better to use == operator. There is one exception to the rule and that is for strings, since string is a reference type but == operator is overloaded in .Net framework to check for equality.

those calls are equivalent, aren't they?

They are equivalent.

Upvotes: 3

Related Questions