Converting int to char in c#. But after converting the value, char holds nothing

245 views Asked by At
char chr1 = '9';
int num = 9;
char chr2 = (char)num;
if(chr1 == chr2)
   Console.WriteLine("It worked");
else 
   Console.WriteLine("It did not work");
Console.WriteLine(chr2.GetType().Name);
Console.Write(chr2);

I want to convert an int to a char and compare it with another char. When i ran this code the output is

It did not work
Char 
        

So it converts int to a char successfully but chr2 has no value it prints nothing (but its move the cursor)
Hence it has no value if is not working but i didn't understand why chr2 has no value.

1

There are 1 answers

2
Serge On

just use this

char chr2 = Convert.ToChar(num.ToString());

or thanks to @Charlieface

char chr2 =  num.ToString()[0];

this is because

num=Convert.ToByte(9); //9   it is invisible ASCII code - horisontal tab
num=Convert.ToByte('9') //57  it is visible ASCII code '9'