Search code examples
c#unicodechar

In C# how to get minimum and maximum value of char printed in Unicode format?


According to MSDN the minimum value of char is U+0000 and maximum value of char is U+ffff

I have written the following code to print the same:

using System;
using System.Collections.Generic;
using System.Linq;

namespace myApp {
    class Program {
        static void Main() {
            char min = char.MinValue;
            char max = char.MaxValue;
            Console.WriteLine($"The range of char is {min} to {max}");
        }
    }
}

But I am not getting the output in the format U+0000 and U+ffff.

How to get it?


Solution

  • Your problem is that char when formatted into a string is already represented as the character. I mean the char with value 0x30 is represented as 0, not as 48.

    So you need to cast those values as int and display them hexadecimal (using the format specifier X):

    int min = char.MinValue; // int - not char
    int max = char.MaxValue;
    Console.WriteLine($"The range of char is U+{min:x4} to U+{max:x4}");
    

    to see their numerical (hexadecimal) value.

    Result:

    The range of char is U+0000 to U+ffff
    

    See: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated