Ravi Gupta
Ravi Gupta

Reputation: 6460

Is there any way to set Encoding.UTF8 instance provide BOM as false

I know that we can create an instance of UTF8Encoding which doesn't provide a Unicode byte order mark by using UTF8Encoding(false). But I also came across a another way of getting a reference to an UTF8Encoding instance is by Encoding.UTF8. The question is: Can we set provide BOM property of the static Encoding.UTF8 instance as false, or it will always provide BOM?

Upvotes: 0

Views: 185

Answers (1)

jlew
jlew

Reputation: 10591

Encoding.UTF8 returns a static, default instance, which will always include the BOM

    [__DynamicallyInvokable]
    public static Encoding UTF8
    {
      [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] get
      {
        if (Encoding.utf8Encoding == null)
          Encoding.utf8Encoding = (Encoding) new UTF8Encoding(true);
        return Encoding.utf8Encoding;
      }
    }

I should note that the flag is stored in a private boolean field which you could probably set to false via reflection, but that is not a good idea for a number of reasons.

Upvotes: 2

Related Questions