user1122152
user1122152

Reputation:

Compare two char[] arrays in C#

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.

Upvotes: 2

Views: 10467

Answers (1)

Robert Harvey
Robert Harvey

Reputation: 180777

== 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");
}

Upvotes: 9

Related Questions