0

I am new to C# and just comparing two arrays... both arrays should be equal, as their values are same, but result is always false... not sure why.

char[] arOne =  { 'a', 'b', 'c', '\u0000' };
char[] arTwo = new char[] { 'a', 'b', 'c', '\u0000' };
Console.WriteLine(" Two arrays are equal ? ...{0}", (arOne == arTwo) ? "true" : "false");
gpmurthy
  • 2,397
  • 19
  • 21
user3008418
  • 13
  • 1
  • 1
  • 3
  • http://stackoverflow.com/questions/713341/comparing-arrays-in-c-sharp – Soner Gönül Nov 19 '13 at 11:38
  • The `==` operator on reference types is conducting a reference comparison (are those references pointing to the same object) not the content of underlying objects. – tpeczek Nov 19 '13 at 11:38

5 Answers5

5

Try and use this

Enumerable.SequenceEqual Method (IEnumerable, IEnumerable)

bool areEqual = arOne.SequenceEqual(arTwo);

What you are doing is comparing object references and not the actual contents of the collections.

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
3

The == operator just compares the references, if they are not the same it returns false. You could use SequenceEqual:

bool bothSameChars = arOne.SequenceEqual(arTwo);

SequenceEqualtakes also the order into account, if that doesn't matter you could use HashSet<Char> and it's SetEquals method which is very efficient:

HashSet<Char> charset1 = new HashSet<Char>(arOne);
HashSet<Char> charset2 = new HashSet<Char>(arTwo);
bothSameChars = charset1.SetEquals(charset2);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

Use this code:

Console.WriteLine("Two arrays are equal? ...{0}", arOne.Intersect(arTwo).Any() ? "true" : "false");
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
0

Consider the following Code...

Console.WriteLine(" Two arrays are equal ? ...{0}", Enumerable.SequenceEqual(arOne, arTwo) ? "true" : "false");

Good Luck!

gpmurthy
  • 2,397
  • 19
  • 21
0

You are currently checking the REFERENCE to two objects and check if those are equal, which they obviously are not. What you want to do is check if their CONTENT AND SEQUENCE are equal, for which they invented the awesome function .SequenceEqual(). Your code will be something like

char[] arOne = { 'a', 'b', 'c', '\u0000' };
char[] arTwo = new char[] { 'a', b', 'c', '\u0000' };
Console.WriteLine(" Two arrays are equal ? ... {0}", (arOne.SequenceEqual(arTwo)));

Because SequenceEqual() already returns a boolean, you don't even have to add the ? "true" : false" anymore.

Voidpaw
  • 910
  • 1
  • 5
  • 18