System.Text.Encoding.GetMaxCharCount Method

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

Syntax

public abstract int GetMaxCharCount (int byteCount)

Parameters

byteCount
The number of bytes to decode.

Returns

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

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, it 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.

Encoding.GetMaxCharCount(int) retrieves a worst-case number, including the worst case for the currently selected System.Text.DecoderFallback. If a fallback is chosen with a potentially large string, Encoding.GetMaxCharCount(int) retrieves large values.

In most cases, this method retrieves reasonable numbers for small strings. For large strings, you might have to choose between using very large buffers and catching errors in the rare case that a more reasonable buffer is too small. You might also want to consider a different approach using erload:System.Text.Encoding.GetCharCount or erload:System.Text.Decoder.Convert.

Encoding.GetMaxCharCount(int) has no relation to Encoding.GetBytes(string). If your application needs a similar function to use with Encoding.GetBytes(Char[]), it should use Encoding.GetMaxByteCount(int).

When using Encoding.GetMaxCharCount(int), your application should allocate the output buffer based on the maximum size of the input buffer. If the output buffer is constrained in size, the application might use the Convert method.

Note that Encoding.GetMaxCharCount(int) considers the worst case for leftover bytes from a previous encoder operation. For most code pages, passing a value of 0 to this method retrieves values greater than or equal to 1.

Note:

GetMaxCharCount(N) is not necessarily the same value as N* GetMaxCharCount(1).

Requirements

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