0

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");
  }
  • 1
    Arrays are reference types, that means, even if you create two arrays with the same elements, they are two different objects. If you want to compare the elements, you can use for example [SequenceEquals](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequenceequal?view=net-5.0) – Steeeve Nov 01 '21 at 12:28
  • 4
    If you just wan to check if the array is empty do `if(hobbies.Length == 0)` or using Linq `if(!hobbies.Any())` – juharr Nov 01 '21 at 12:30

2 Answers2

1

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])
Maroun
  • 94,125
  • 30
  • 188
  • 241
0

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();
    }
  • The accepted answer already contains the solution you provided. Please edit your answer with further information if you believe it better answers the question. – Tvde1 Nov 01 '21 at 13:20