ASCIIEncoding::GetMaxByteCount Method (Int32)

 

Calculates the maximum number of bytes produced by encoding the specified number of characters.

Namespace:   System.Text
Assembly:  mscorlib (in mscorlib.dll)

public:
virtual int GetMaxByteCount(
	int charCount
) override

Parameters

charCount
Type: System::Int32

The number of characters to encode.

Return Value

Type: System::Int32

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

Exception Condition
ArgumentOutOfRangeException

charCount is less than zero.

-or-

The resulting number of bytes is greater than the maximum number that can be returned as an integer.

The GetByteCount method calculates the exact array size required by the GetBytes method to store the resulting bytes, whereas the GetMaxByteCount method calculates the maximum array size. The GetByteCount method generally allocates less memory, but the GetMaxByteCount method generally executes faster.

GetMaxByteCount is a worst-case number, including the worst case for the currently selected EncoderFallback. If you choose a replacement fallback with a potentially large string, GetMaxByteCount can return large values.

The GetMaxByteCount method considers potential leftover surrogates from a previous encoding operation. As a result, if the ASCIIEncoding object uses the default replacement fallback, or if a custom replacement fallback has been defined with a single possible fallback character, the method returns charCount + 1. If the ASCIIEncoding object uses a replacement fallback with more than one possible fallback character, the method returns n * (charCount + 1), where n is the maximum number of fallback characters.

GetMaxByteCount has no relation to GetChars. If your application needs a similar function to use with GetChars, it should use GetMaxCharCount.

System_CAPS_noteNote

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

The following example demonstrates how to use the GetMaxByteCount method to calculate the bytes required to encode a specified number of characters.

using namespace System;
using namespace System::Text;
int main()
{
   ASCIIEncoding^ ascii = gcnew ASCIIEncoding;
   int charCount = 2;
   int maxByteCount = ascii->GetMaxByteCount( charCount );
   Console::WriteLine( "Maximum of {0} bytes needed to encode {1} characters.", maxByteCount, charCount );
}

Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Return to top
Show: