PakiPat
PakiPat

Reputation: 1065

Why do I get a "Cannot implicitly convert type 'char[]' to 'string' [C# programs]"

... when I try this in C#:

string reversedName;
reversedName = name.ToCharArray().Reverse().ToArray();

But not when I try this:

string reversedName = new string (name.ToCharArray().Reverse().ToArray());

? And when I try adding chaining a To.String() to the end of the first method, the Runtime doesn't throw an exception but returns: System.Char[]

I'm looking for an explanation on why the compiler seems to not be able to implicitly convert char[] to string: * except when, apparently, calling new string, * even when we chain the ToString() function to the end there.

Upvotes: 0

Views: 3974

Answers (2)

Guilherme
Guilherme

Reputation: 5341

The ToString() on an Char Array object will return System.Char[] because it's the default and expected behavior. The compiler cannot assume that you want to join every char into one string, and return that string.

The correct way is to use new string(char[]).

You can also always use a Extension class to add a extension method.

public static class Extensions
{
    public static string ConvertToString(this char[] array)
    {
        return new string(array);
    }
}

Usage:

string s = array.ConvertToString();

Upvotes: 1

Petr Adam
Petr Adam

Reputation: 1437

When you try

string reversedName = new string (name.ToCharArray().Reverse().ToArray());

you are creating string with its constructor. As you can see, first parameter is array of chars: https://msdn.microsoft.com/en-us/library/ms131424(v=vs.110).aspx

But here

reversedName = name.ToCharArray().Reverse().ToArray();

you are returning an array (with .ToArray() at the end), which is obviously not assignable to variable of type string.

Calling ToString() on array will print its type System.Char[], as you already noticed.

Upvotes: 2

Related Questions