System.Text.Encoding.GetCharCount Method

When overridden in a derived class, calculates the number of characters produced by decoding all the bytes in the specified byte array.

Syntax

public virtual int GetCharCount (byte[] bytes)

Parameters

bytes
The byte array containing the sequence of bytes to decode.

Returns

The number of characters produced by decoding the specified sequence of bytes.

Exceptions

TypeReason
ArgumentNullException bytes is null.

Remarks

To calculate the exact array size required by Encoding.GetChars(Byte[]) to store the resulting characters, the application should use Encoding.GetCharCount(Byte[]). To calculate the maximum array size, the application should use Encoding.GetMaxCharCount(int). The Encoding.GetCharCount(Byte[]) method generally allows allocation of less memory, while the Encoding.GetMaxCharCount(int) method generally executes faster.

The Encoding.GetCharCount(Byte[]) method determines how many characters result in decoding a sequence of bytes, and the Encoding.GetChars(Byte[]) method performs the actual decoding. The Encoding.GetChars(Byte[]) method expects discrete conversions, in contrast to the Decoder.GetChars(Byte[], int, int, Char[], int) method, which handles multiple passes on a single input stream.

Several versions of Encoding.GetCharCount(Byte[]) and Encoding.GetChars(Byte[]) are supported. The following are some programming considerations for use of these methods:

  • The application might need to decode multiple input bytes from a code page and process the bytes using multiple calls. In this case, your application probably needs to maintain state between calls.

  • If the application handles string outputs, it is recommended to use the Encoding.GetString(Byte[]) method. Since this method must check string length and allocate a buffer, it is slightly slower, but the resulting string type is to be preferred.

  • The byte version of Encoding.GetChars(Byte*, int, Char*, int) allows some fast techniques, particularly with multiple calls to large buffers. Bear in mind, however, that this method version is sometimes unsafe, since pointers are required.

  • If your application must convert a large amount of data, it should reuse the output buffer. In this case, the Encoding.GetChars(Byte[], int, int, Char[], int) version that supports output character buffers is the best choice.

  • Consider using the erload:System.Text.Decoder.Convert method instead of Encoding.GetCharCount(Byte[]). The conversion method converts as much data as possible and throws an exception if the output buffer is too small. For continuous decoding of a stream, this method is often the best choice.

Requirements

Namespace: System.Text
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0