Array.ToString () returns System.Char [] C #

I am creating a hangman game, at the beginning of the game the word that the player has to guess is printed as stars. I just started doing it again, trying to write it once, and just messed up code that I couldn't fix. So I decided that it would be better to write it again. The only problem is when I try to get my printable array using array.ToString (); it just returns System.char []. See below.

code:

class Program
{
    static void Main(string[] args)
    {
        string PlayerOneWord;
        string PlayerTwoGuess;
        int lives = 5;

        Console.WriteLine("Welcome to hangman!\n PLayer one, Please enter the word which player Two needs to guess!");
        PlayerOneWord = Console.ReadLine().ToLower();

        var stars = new char[PlayerOneWord.Length];
        for (int i = 0; i < stars.Length ; i++)
        {
                stars[i] = '*';
        }

        string StarString = stars.ToString();

        Console.Write("Word to Guess: {0}" , StarString);

        Console.ReadLine();
    }
}

      

output:

Output

The output should contain Word to guess: Hello

.

Please explain why this is not the first time I have encountered this problem.

+3


source to share


3 answers


Calling ToString

only a simple array will return "T[]"

regardless of type T

. It has no special treatment for char[]

.

To convert a char[]

to string

, you can use:

string s = new string(charArray);

      



But there is an even simpler solution for your specific problem:

string stars = new string('*', PlayerOneWord.Length);

      

The constructor public String(char c, int count)

repeats c

count

once.

+7


source


The variable stars

is an array of characters. It is for this reason that you are getting this error. As stated on MSDN

Returns a string representing the current object.



To get a string from characters in this array, you can use this:

 Console.Write("Word to Guess: {0}" , new String(stars));

      

+2


source


The correct way to do it is:

string StarString = new string(stars);

      

ToString () calls the standard implementation of the ToString method of the Array class, which is the same for all arrays and, like an object, returns only the fully qualified class name.

+2


source







All Articles