0

a quite simple code:

string str = "hello  world";
            
Console.WriteLine(str.GetType());

Console.WriteLine("str.Reverse().ToString():");
Console.WriteLine(str.Reverse().ToString());

and got the following output:

System.String str.Reverse().ToString(): System.Linq.Enumerable+ReverseIterator`1[System.Char]

the question is , why there is the 'ReverseIterator`1' error ? thanks.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132

2 Answers2

4

String does not have instance method Reverse, it is actually an extension method Enumerable.Reverse<TSource>(IEnumerable<TSource>) available on string due to the fact that it implements IEnumerable<char>:

public sealed class String : ICloneable, 
    IComparable, 
    IComparable<string>, 
    IConvertible, 
    IEquatable<string>, 
    System.Collections.Generic.IEnumerable<char>

Reverse returns IEnumerable<char> with underlying implementation missing overload for ToString so it outputs type name. I.e. next to lines will have the same output:

Console.WriteLine(str.Reverse().ToString());
Console.WriteLine(str.Reverse().GetType());

You can reverse string next "quick and dirty" solution:

var reversed = new string(str.Reverse().ToArray());

Or select one of answers provided here.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
0

String does not have instance method Reverse. Your code str.Reverse().ToString() is actually splitting your string char-by-char and then reversing it using the Reverse method in the Array instance.

What you can do is manually split your string into a char array, reverse the array using the Reverse method in the Array instance and then join it using the Join method in String instance. Something like this:

string str = "hello  world";

Console.WriteLine(str.GetType());

// Manually split the string into a char array,
// reverse the array and then join it.
Console.WriteLine("str.ToCharArray().Reverse():");
string NewStr = string.Join("", str.ToCharArray().Reverse());

Console.WriteLine(NewStr);
// Output: "dlrow  olleh"

But if you want to stick with the code you wrote then you can do something like this:

string str = "hello  world";

Console.WriteLine(str.GetType());

string NewStr = "";
Console.WriteLine("str.Reverse().ToString():");

// Split the string into a char array,
// reverse the char array and append the chars to a new string.
foreach (var i in str.Reverse())
{
    NewStr += i.ToString();
}

Console.WriteLine(NewStr);
// Output: "dlrow  olleh"

Hope it helped :)

Light-Lens
  • 81
  • 7
  • _"is actually splitting your string char-by-char and then reversing it using the Reverse method in the Array instance"_ - no, it is not, as far as I [can see](https://source.dot.net/#System.Linq/System/Linq/Reverse.cs,25). And [here](https://source.dot.net/#System.Private.CoreLib/String.cs,577) – Guru Stron Feb 05 '22 at 09:57
  • @GuruStron I said this just to make it easier for the questioner to understand. – Light-Lens Feb 05 '22 at 10:22