Home > Enterprise >  ToString method for char array
ToString method for char array

Time:03-28

I read a String from the Console and put it in the array called 'array' then I output the 'array' to the Console and it is fine, then I apply the ToString method to the 'array' and put it in a String called 'jj', then I out put the 'jj' and I get this : System.Char[]

I have a good reason why I am doing this, It is just that I sis not show you the whole program.

I do not understand why. Please help me.

 String uno = Console.ReadLine();
        char[] array = uno.ToCharArray();
 Console.WriteLine(array);
        String jj = array.ToString();
        Console.WriteLine(jj);

CodePudding user response:

The first example (char[] array) will print fine because Console.WriteLine accepts an overload of char array -- see here.

The second example (string jj) does not work because ToString is not overriden in System.Array, which is what your character array derives from, so Object.ToString will be called instead, as all types derive from System.Object. This is why System.Char[] is printed -- the type of this object.

You can construct a new string from the char array like so:

string jj = new string(array);
Console.WriteLine(jj);

CodePudding user response:

There's a constructor for string that accepts a char[]. You should therefore try this:

var jj = new string(array);
Console.WriteLine(jj);
  •  Tags:  
  • c#
  • Related