Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between UTF8Encoding.UTF8.GetBytes and Encoding.UTF8.GetBytes?

Today I saw a code in which UTF8Encoding.UTF8.GetBytes and Encoding.UTF8.GetBytes is used. Is there any difference between them?

like image 858
Vaysage Avatar asked Mar 18 '11 12:03

Vaysage


4 Answers

No difference at all.

Encoding.UTF8 is UTF8Encoding.

From MSDN (Encoding.UTF8):

This property returns a UTF8Encoding object

Instead of UTF8Encoding.UTF8.GetBytes you can simply call UTF8Encoding.GetBytes.

like image 157
Oded Avatar answered Nov 09 '22 15:11

Oded


There is at least one difference. Encoding.UTF8 will write BOM while UTF8Encoding will not (by default). Check this out:

using System;
using System.Text;

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

        Console.WriteLine("utf8 preamble:");
        ShowArray(utf8.GetPreamble());

        Console.WriteLine("utf8EmitBOM:");
        ShowArray(utf8EmitBOM.GetPreamble());

        Console.WriteLine("Encoding.UTF8 preamble:");
        ShowArray(Encoding.UTF8.GetPreamble());
   }

    public static void ShowArray(Array theArray) {
        foreach (Object o in theArray) {
            Console.Write("[{0}]", o);
        }
        Console.WriteLine();
    }
}
like image 41
pengu1n Avatar answered Nov 09 '22 13:11

pengu1n


UTF8Encoding inherits its static UTF8 property from Encoding, so they are in fact the same property.

like image 29
Jon Hanna Avatar answered Nov 09 '22 14:11

Jon Hanna


These are just two different ways to access the UTF8Encoding class and call its static member GetBytes.

like image 3
naivists Avatar answered Nov 09 '22 15:11

naivists