C# `Char.ConvertFromUtf32()`: Converting Unicode Code Points to Characters

Learn how to convert Unicode code points to their corresponding characters in C# using the `Char.ConvertFromUtf32()` method. This tutorial explains Unicode encoding, demonstrates converting code points to characters, and highlights its use in handling various international characters and scripts.



Using `Char.ConvertFromUtf32(Int32)` in C# for Unicode Character Conversion

Introduction

The `Char.ConvertFromUtf32(Int32)` method in C# converts a Unicode code point (a numerical representation of a character) into its corresponding character as a string. This is essential for working with characters from various languages and scripts.

Understanding Unicode Code Points

Unicode is a standard that assigns unique numerical values (code points) to characters. These code points are integers. `Char.ConvertFromUtf32()` takes a Unicode code point as input and returns the character represented by that code point.

`Char.ConvertFromUtf32(Int32)` Method Syntax

Method Syntax

public static string ConvertFromUtf32(int utf32);

Parameter

utf32: An integer representing the Unicode code point.

Return Value

A string containing the character corresponding to the input code point.

Example 1: Converting a Single Code Point

Example 1: Single Code Point

using System;

class UnicodeCharacterRepresentation {
    static void Main(string[] args) {
        int unicodeCodePoint = 8364; // Euro symbol
        string euroSymbol = Char.ConvertFromUtf32(unicodeCodePoint);
        Console.WriteLine($"Euro Symbol: {euroSymbol}"); // Output: Euro Symbol: €
    }
}

Example 2: Dynamic String Construction

Example 2: Dynamic String Construction

using System;

class DynamicStringConstruction {
    static void Main(string[] args) {
        int codePoint1 = 65; // 'A'
        int codePoint2 = 66; // 'B'
        string dynamicString = Char.ConvertFromUtf32(codePoint1) + Char.ConvertFromUtf32(codePoint2);
        Console.WriteLine($"Dynamic String: {dynamicString}"); // Output: Dynamic String: AB
    }
}

Example 3: Parsing External Data

Example 3: Parsing External Data

using System;
using System.Linq;

class ParsingExternalData {
    static void Main(string[] args) {
        int[] codePointsFromFile = { 72, 101, 108, 108, 111 }; //'Hello'
        string parsedString = string.Join("", codePointsFromFile.Select(Char.ConvertFromUtf32));
        Console.WriteLine($"Parsed String: {parsedString}"); // Output: Parsed String: Hello
    }
}

Conclusion

The `Char.ConvertFromUtf32(Int32)` method is valuable for handling Unicode characters in C#. While it simplifies working with diverse character sets, remember to consider its performance implications, especially when processing large amounts of data.