Converting string to char array?

10.6k Views Asked by At

Can anybody explain me why this is happening?

class Program
{
    static char[] ch = new char[2];
    static string name = "Ivankata";

    static void Main(string[] args)
    {
        inputChar();
    }

    static void inputChar()
    {
        ch = name.ToCharArray();
        Console.WriteLine(ch);
    }
}

My char array named ch accepts only 2 chars however when I convert my string "Ivankata" to char array it works somehow? Shouldn't it cut the remaining "ankata" and show only "iv"? Can anybody explain what's going on here?

2

There are 2 best solutions below

5
lorisleitner On

string.ToCharArray() creates a new char array iternally and you store the reference to new array in ch. The old array with a length of two is not referenced anymore and will be collected by the Garbage Collector soon.

0
Emre Kabaoglu On

Shouldn't it cut the remaining "ankata" and show only "iv"?

No, It doesn't work like that. You can assign items to array in a simple loop.

for (int i = 0; i < ch.Length; i++)
{
    ch[i] = name[i];
}
Console.WriteLine(ch);