6

If I use:

A) var targetEncodingA = Encoding.ASCII;

and

B) var targetEncodingB = new ASCIIEncoding();

then both targetEncoding0 and targetEncoding1 are of the same type.

Are there any preferred scenarios and/or advantages/disadvantages when to use A or B?

(besides creating new instance by constructor each time I use it)

rudolf_franek
  • 1,795
  • 3
  • 28
  • 41
  • possible duplicate of [Difference Between ASCIIEncoding and Encoding](http://stackoverflow.com/questions/5636372/difference-between-asciiencoding-and-encoding) – Ehsan Jan 02 '14 at 10:04
  • It is just a convenience property. You'd prefer using Encoding.ASCII because it is convenient, nothing more. – Hans Passant Jan 02 '14 at 10:16
  • @NoOne - both questions target the same specific topic still the content is slightly different. But thanks for the comment. – rudolf_franek Jan 02 '14 at 10:58

2 Answers2

10

Here is the Encoding.ASCII implement detail (from Encoding.cs):

private static volatile Encoding asciiEncoding;

public static Encoding ASCII
{
  {
    if (Encoding.asciiEncoding == null)
      Encoding.asciiEncoding = (Encoding) new ASCIIEncoding();
    return Encoding.asciiEncoding;
  }
}

The main difference is the return type differs, which depends on what type you wish to use (ASCIIEncoding vs Encoding), and Encoding is the base class.

From a performance perspective, Encoding.ASCII is the preference.

Jerry Bian
  • 3,998
  • 6
  • 29
  • 54
4

I prefer Encoding.ASCII in all cases, it is a static property. It avoids creating a new instance each time it is needed (singleton).

Personnaly, I avoid using the new keyword when possible when a static class can do that for you. I will add that Encoding.ASCII is shorter to write than new ASCIIEncoding().

colinfang
  • 20,909
  • 19
  • 90
  • 173
AlexH
  • 2,650
  • 1
  • 27
  • 35