Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two objects is string and is equal

Tags:

c#

values is an object array. I need to check whether the 3rd and 4th elements are strings. If this is the case, I need to check whether they're equal.

Here is how I did it:

if ( values[2] is string && 
     values[3] is string && 
     ((values[2] as string) == (values[3] as string)))
{
    return false;
}

Is there a simpler or shorter way to do this?

like image 487
Nayana Adassuriya Avatar asked Jun 22 '26 01:06

Nayana Adassuriya


2 Answers

I think the string.Equals(object) method is the simplest to use here.

 result = string.Equals(value[2], value[3]);

From MSDN

returns true if obj is a String and its value is the same as this instance; otherwise, false. If obj is null, the method returns false.

like image 110
Resley Rodrigues Avatar answered Jun 23 '26 16:06

Resley Rodrigues


Here's how I would do it:

return values[2] is string && values[2].Equals(values[3]);

It's sufficient to know that one of both objects is a string. If it then equals the other object, this guarantees that the other object is also a string.

Also, note the use of Equals() instead of == to guarantee a comparison of the string contents as opposed to the object references.

like image 27
Robby Cornelissen Avatar answered Jun 23 '26 14:06

Robby Cornelissen