Correct way to compare integers

I'm not an expert in C #, but I know that I shouldn't just use ==

when comparing strings. Is there a similar method .Equals

that I should use when comparing ints?

For example, I would like to do something like:

if (someInt == 2) {}


Is this acceptable in C #?


source to share

4 answers

I shouldn't just use == when comparing strings

Why not? (Assuming a different culture or some other default comparison mechanism works for you.) This is a perfectly reasonable operator for strings, as it is for ints. It tells you if the two values ​​are equal, as you would expect.

This is not the only way to compare two strings or ints for equality, but it is definitely the correct one.



Since int

is a value type, it cannot be null


Hence, you can use ==

just fine.

However, if you have a class MyInteger

(a wrapper class for a value type int

that inherits from a type Object

) that can be an object null

that does not contain int

within it. See. This MSDN against Boxing and Unboxing, which int

is placed in a box and assignedObject


Back to the question, you can use == just fine for types int

, here are some other alternatives:

and. CompareTo


eg: 5.CompareTo(6) //returns -1

This will return -1 if the first int is less, 0 - they are equal and 1 if the first int is greater. This method is similar to operators < > ==


b. Int32.Equals

 This is identical ==

as it returns a true / false boolean. See an example from MSDN here . However, there is a difference in this method compared to == for boxed int since Jon Skeet is detailed in this SO question , it has to do with boxing and unboxing which I was talking about



I think I can sort this out a bit. The choice to use .Equals over == in String

comes from Java. In Java, it is String

wrapped and handled as an object, which can cause some problems, including null pointer exceptions. This does not occur in C #, however, because it String

is a base type and String.Equals(a, b)

is defined as a == b

. String.Equals gives you several options, allowing you to add a comparison type. This is a slight advantage to String.Equals, but under no circumstances should you always use one over the other. However, I felt it should be noted that String.Equals should be used in Java as the two languages ​​are very similar and might be confusing for a newbie. However, all the above answers in relation to int a == int b


are valid, I would use ==

more often for ints, because it is more common practice.



You can absolutely use == for strings in C #, we have operator overrides.



All Articles