Search code examples
c#charconsole.writeline

Can't write char in console


I want to write a char in the console.

This is my code.

using System;

namespace bla
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            int d = 5;
            char e = (char)d;
            Console.WriteLine("my Char: " + e);
            Console.WriteLine("my Char: " + e.ToString ()); // also doesn't work
        }
    }
}

Instead I just see "my Char: " as an output, instead the expected "my Char: 5".


Solution

  • casting 5 to char gives you 5th value from this ASCII table.

    It does not show anything in console because its not a printable character.

    If you notice the numbers in table start from 48 (i.e number 0) to 57 (i.e number 9).

    So you have to do this.

    int d = 5;
    char e = (char)(d + 48);
    Console.WriteLine("my Char: " + e);
    Console.WriteLine("my Char: " + (char)(5 + '0')); // or