I am expecting this code to write "no hobbies" to the console. However, nothing is output. Why is this?
string[] hobbies = new string[0];
if (hobbies == new string[0])
{
Console.WriteLine("no hobbies");
}
CodePudding user response:
You're comparing arrays, ==
in this case compares references and not values. If you want to compare the arrays' content, you could use SequenceEqual
:
hobbies.SequenceEqual(new string[0])
CodePudding user response:
Array content can be compared using array.Equal(another_array) or array.SequenceEqual(another_array) . try this:
static void Main(string[] args)
{
string[] hobbies = new string [0];
if(hobbies.SequenceEqual(new string[0]))
{
Console.WriteLine("no hobbies");
}
Console.ReadKey();
}