Veselin Stoychev
Veselin Stoychev

Reputation: 61

C# -> string.Reverse(); - do not work in # using System.Linq;

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);
        }
    }
}

Upvotes: 5

Views: 24747

Answers (2)

CEH
CEH

Reputation: 5909

.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.

Upvotes: 8

Charles
Charles

Reputation: 3071

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

Upvotes: 10

Related Questions