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);
        }
    }
}
4
  • 2
    Linq's Reverse treats a string as an array of characters, and returns a collection of characters, not a string. Commented Nov 9, 2019 at 19:04
  • The compiler says you a) The return value of String.Reverse() is not a string, but a IEnumerable<char> (a special use case of the array). b) It can not find any implicit conversions between IEnumerable<char> and string Commented Nov 9, 2019 at 19:07
  • Note though that reversing a string character by character will produce the wrong result in lots of cases. Commented Nov 9, 2019 at 19:16
  • Does this answer your question? Best way to reverse a string Commented Nov 9, 2019 at 19:20

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

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 :(
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)
I missed a .ToArray() cast on the new string() call. The code compiles and produces a reversed string.
It does now. It's always worth testing the code you post. The ToCharArray is still unnecessary though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.