Chris Buege
Chris Buege

Reputation: 59

Error while attempting to create a program to reverse a string

Everything I have read on the internet makes me think this program should run but I keep getting an error. The error states:

"Cannot implicitly convert type 'system.collections.generic.IEnumerable' to 'string'. An implicit conversion exists".

Am I missing something?

class Program
{
    static void Main(string[] args)
    {
        string entry;

        Console.Write("Input String: ");
        entry = Console.ReadLine();

        entry = entry.Reverse();
        //Error occurs here ^             

        Console.Write(entry);

        Console.ReadKey(); 
    }
}

Upvotes: 2

Views: 376

Answers (1)

Grant Winney
Grant Winney

Reputation: 66459

The call to entry.Reverse() gives you a collection of characters.

You can use the constructor of string that accepts a character array, to store the value.

var myReversedString = new string(entry.Reverse().ToArray());

Or to just write it to the console:

Console.Write(entry.Reverse().ToArray());

The WriteLine() method has a lot of overloads, and can accept a lot of different parameter types, but a list is not one of them. So it uses the overload that accepts an object, then calls ToString() on it, which outputs the class name... so you see something like:

System.Linq.Enumerable+<ReverseIterator>d__a0`1[System.Char]

Upvotes: 5

Related Questions