Get a Unicode character name from a Rune in .NET

 
 
  • Gérald Barré

If you have a Rune and want its Unicode name (for example GRINNING FACE for 😀), there is no built-in API in .NET today.

Here are two practical options:

  • Use the ICU library available on the operating system
  • Use the Meziantou.Framework.Unicode NuGet package

#Method 1: Use ICU from the OS

ICU exposes u_charName, which returns the Unicode name for a code point.

C#
using System;
using System.Runtime.InteropServices;
using System.Text;

public static class IcuNative
{
    private const string IcuLib = "icuuc";

    private enum UCharNameChoice
    {
        U_UNICODE_CHAR_NAME = 0,
    }

    private enum UErrorCode
    {
        U_ZERO_ERROR = 0,
    }

    [DllImport(IcuLib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "u_charName")]
    private static extern int u_charName(
        int codepoint,
        UCharNameChoice nameChoice,
        byte[] buffer,
        int bufferLength,
        ref UErrorCode errorCode);

    public static string GetCharName(Rune rune)
    {
        var buffer = new byte[128];
        var error = UErrorCode.U_ZERO_ERROR;

        int length = u_charName(
            rune.Value,
            UCharNameChoice.U_UNICODE_CHAR_NAME,
            buffer,
            buffer.Length,
            ref error);

        if (error != UErrorCode.U_ZERO_ERROR)
            throw new InvalidOperationException($"ICU error: {error}");

        return Encoding.ASCII.GetString(buffer, 0, length);
    }
}

Usage:

C#
var rune = new Rune(0x1F600); // 😀
Console.WriteLine(IcuNative.GetCharName(rune)); // GRINNING FACE

This option is nice when you want to avoid adding Unicode data files to your app because ICU is already provided by the OS.

#Method 2: Use Meziantou.Framework.Unicode

If you prefer a managed API with no native interop code, use Meziantou.Framework.Unicode.

Shell
dotnet package add Meziantou.Framework.Unicode
C#
var rune = new Rune(0x1F600); // 😀
Console.WriteLine(Meziantou.Framework.Unicode.GetCharacterInfo(rune).Value.Name); // GRINNING FACE

This option is portable and easy to use, but it increases application size because the Unicode data ships with your app.

#Which one should you choose?

  • ICU: depends on OS-provided ICU, but keeps your app smaller
  • Meziantou package: independent from OS ICU details, but larger app size

#Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?