3

I tried to make Palindrome program as small as possible. However, this program is giving logical error. When I enter palindrome string it gives "False" as result which is opposite of what is expected.

char[] phrase;
Console.WriteLine((phrase = Console.ReadLine().ToArray())==phrase.Reverse().ToArray());
Console.ReadLine();

I do not want to increase number of statements of this program.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

3 Answers3

5

In .NET, arrays do not have an overloaded equality operator. Use Enumerable.SequenceEquals.

Reading your code more thoroughly, you are making things more complicated than necessary.

    string phrase = Console.ReadLine();
    var reversedPhrase = phrase.Reverse(); //Type is IEnumerable<char>
    Console.WriteLine(phrase.SequenceEquals(reversedPhrase));

I recommend that you don't burry side-effects inside of expressions in the way you did. That code could well have been a test question to see if a student can work it out.

usr
  • 168,620
  • 35
  • 240
  • 369
1

If you want to do it by array then you can try this

char[] phrase;
Console.WriteLine(phrase = Console.ReadLine().ToArray().SequenceEqual(phrase.Reverse().ToArray()));
Console.ReadLine();

just like usr said use sequenceequal

Sid M
  • 4,354
  • 4
  • 30
  • 50
0

Since you created 2 different array and arrays are reference type, == checks for reference equality, not value.

You can use Enumerable.SequenceEqual instead which returns;

true if the two source sequences are of equal length and their corresponding elements are equal according to the default equality comparer for their type;

Console.WriteLine(myString.SequenceEqual(myString.Reverse()));
Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364