UTF8Encoding Constructor (Boolean)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Initializes a new instance of the UTF8Encoding class. A parameter specifies whether to provide a Unicode byte order mark.

Namespace:   System.Text
Assembly:  mscorlib (in mscorlib.dll)

public UTF8Encoding(
	bool encoderShouldEmitUTF8Identifier


Type: System.Boolean

true to specify that the GetPreamble method returns a Unicode byte order mark; otherwise, false. See the Remarks section for more information.

This constructor creates an instance that does not throw an exception when an invalid encoding is detected.


For security reasons, you should enable error detection by calling a constructor that includes a throwOnInvalidBytes parameter and setting its value to true.

The encoderShouldEmitUTF8Identifier parameter controls the operation of the GetPreamble method. If true, the method returns a byte array containing the Unicode byte order mark (BOM) in UTF-8 format. If false, it returns a zero-length byte array. However, setting encoderShouldEmitUTF8Identifier to true does not cause the GetBytes method to prefix the BOM at the beginning of the byte array, nor does it cause the GetByteCount method to include the number of bytes in the BOM in the byte count.

The following example creates a new UTF8Encoding instance and specifies that a Unicode byte order mark prefix should be emitted by the GetPreamble method. The GetPreamble method then returns the Unicode byte order mark prefix.

using System;
using System.Text;

class UTF8EncodingExample {
    public static void Main() {
        UTF8Encoding utf8 = new UTF8Encoding();
        UTF8Encoding utf8EmitBOM = new UTF8Encoding(true);

        Console.WriteLine("utf8 preamble:");


    public static void ShowArray(Array theArray) {
        foreach (Object o in theArray) {
            Console.Write("[{0}]", o);

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top