-4

I'm writing a program that takes a string as input and reverses it. In doing so I came across a behavior that I'm not understanding.

Why doesn't this return a string? Instead it returns System.Char[].

using System;

public static class ReverseString
{
    public static string Reverse(string input)
    {
        if (input.Length == 0)
        {
            return input;
        }
        char[] charArray = input.ToCharArray();
        Array.Reverse(charArray);
        input = charArray.ToString();

        return input;
    }
}

Working Code:

using System;

public static class ReverseString
{
    public static string Reverse(string input)
    {
        if (input.Length == 0)
        {
            return input;
        }
        char[] charArray = input.ToCharArray();
        Array.Reverse(charArray);

        return new string(charArray);
    }
}
jnat
  • 1
  • 3

1 Answers1

1

any method which does not have ToString() implementation returns Object name as string. In this case Char[] (character Array) does not have ToString() implementation hence does not know how to convert character array to string. In this case, you need to create new string.

var reversedString = new string(charArray);
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72