5

This program is not working as expected and I'm not sure why. The error is CS0266 " Error CS0266 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<char>' to 'string'. An explicit conversion exists (are you missing a cast?)

BUT, it should work properly under using System.Linq;

using System;
using System.Linq;
namespace centuryyearsminutes
{
    class Program
    {
        static void Main(string[] args)
        {
            string aa = "Hello World!";
            string bb = aa.Reverse();
            Console.WriteLine(bb);
        }
    }
}
CEH
  • 5,701
  • 2
  • 16
  • 40
Veselin Stoychev
  • 59
  • 1
  • 1
  • 5
  • 2
    Linq's Reverse treats a string as an array of characters, and returns a collection of characters, not a string. – canton7 Nov 09 '19 at 19:04
  • The compiler says you a) The return value of String.Reverse() is not a string, but a `IEnumerable` (a special use case of the array). b) It can not find any implicit conversions between `IEnumerable` and `string` – Christopher Nov 09 '19 at 19:07
  • Note though that reversing a string character by character will produce the wrong result in lots of cases. – canton7 Nov 09 '19 at 19:16
  • Does this answer your question? [Best way to reverse a string](https://stackoverflow.com/questions/228038/best-way-to-reverse-a-string) – canton7 Nov 09 '19 at 19:20

2 Answers2

9

aa.Reverse() returns just an Enumerable<char>

try:

string bb = new string(aa.Reverse().ToArray());

Although this is probably the best way to do it:
https://stackoverflow.com/a/15111719/11808788

Charles
  • 2,721
  • 1
  • 9
  • 15
8

.Reverse() is expecting a collection of characters (docs), not a string. If you do:

string aa = "Hello World!";

var result = aa.ToCharArray().Reverse();

Console.WriteLine(new string(result.ToArray()));

The output is !dlroW olleH.

This should work as expected.

CEH
  • 5,701
  • 2
  • 16
  • 40
  • If you'd like to point out something wrong with an answer, feel free to comment and let me know how I can improve -- downvoting without any explanation doesn't help me understand much here :( – CEH Nov 09 '19 at 19:07
  • 1
    There's no need for ToCharArray (that creates a new unnecessary array), and there's no String ctor which takes an IEnumerable. The downvote is probably because your code won't compile (though it's not mine) – canton7 Nov 09 '19 at 19:08
  • I missed a `.ToArray()` cast on the `new string()` call. The code compiles and produces a reversed string. – CEH Nov 09 '19 at 19:14
  • It does now. It's always worth testing the code you post. The ToCharArray is still unnecessary though. – canton7 Nov 09 '19 at 19:15