1

I have the following C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] st = "stackoverflow".ToCharArray();
            char[] ca = { 's', 't', 'a', 'c', 'k' };
            if (st.Take(5) == ca)
            {
                Console.WriteLine("Success");
            }
            else
            {
                Console.WriteLine("Failure");
            }
        }
    }
}

It's intended to write "Success" to the console but it always prints "Failure". Any help would be really appreciated.

Beau Grantham
  • 3,435
  • 5
  • 33
  • 43
  • 1
    Posting code and saying "what's wrong" is not a great way to start. What have you tried? Are CharArrays considered equal if their contents are equal? Are they compared by pointer value? This seems like a duplicate of http://stackoverflow.com/questions/1389570/c-sharp-byte-array-comparison-issue?lq=1 – gcochard May 31 '13 at 00:16
  • Sorry I just googled for like half hour and didn't found a way to accomplish what I wanted, also I tried every code sample I found but I was unable to make it work. –  May 31 '13 at 00:24

1 Answers1

8

== only compares the references of the two arrays, not their items, and since the two arrays have two different references, your comparison will always return false.

You have to compare the elements of one array to the elements of the other. You can use SequenceEqual to accomplish this.

if (st.Take(5).SequenceEqual(ca))
{
    Console.WriteLine("Success");
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501