Reputation:
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
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