1

Let's say I have the following code point: u1F64A (which is the emoji).

This can be written as:

string monkey = "\u1F64A";

How would I convert a known codepoint (as an integer) to a string at runtime though?

int codepoint = 0xF64A;
string monkey = //?
Garry Pettet
  • 8,096
  • 22
  • 65
  • 103

2 Answers2

3

When I want to play with Emojis in C#, I build a helper class just like this:

public class Emoji
{
    readonly int[] codes;
    public Emoji(int[] codes)
    {
        this.codes = codes;
    }

    public Emoji(int code)
    {
        codes = new int[] { code };
    }

    public override string ToString()
    {
        if (codes == null)
            return string.Empty;

        var sb = new StringBuilder(codes.Length);

        foreach (var code in codes)
            sb.Append(Char.ConvertFromUtf32(code));

        return sb.ToString();
    }
}

This way, I can just do string monkeyEmoji = new Emoji(0xF64A);

It also supports emojis with multiple code points (yes, those exist and are a pain)

Sotiris Panopoulos
  • 1,523
  • 1
  • 13
  • 18
1

Is the above code even compilable? It doesn't compile on my machine. And why should it, \u1F64A is not a valid string.

I think what could work is string monkey = $"{char.ConvertToUtf32((char) 0xF64, 'A')}", but that is just a guess. I just answered to clarify that the first line of code you wrote is not compilable on my machine.

jonzbonz
  • 69
  • 4