UTF8Encoding: GetMaxCharCount

GetMaxCharCount

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



 Public Function GetMaxCharCount(
	  ByVal ByteCount As Long ) As Long

Parameters

ByteCount
[ByVal] Long. The number of bytes to decode.

Return Values

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

Remarks

To calculate the exact array size required by GetCharsEx to store the resulting characters, the application uses GetCharCount. To calculate the maximum array size, the application should use GetMaxCharCount. The GetCharCount method generally allows allocation of less memory, while the GetMaxCharCount method generally executes faster.

GetMaxCharCount is a worst-case number, including the worst case for the currently selected DecoderFallback. If a fallback is chosen with a potentially large string, GetMaxCharCount can return large values.

In most cases, this method returns 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 exceeded. You might also want to consider a different approach using GetCharCount or Encoder.Convert.

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

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

Exceptions

ExceptionCondition
ArgumentOutOfRangeException ByteCount is less than zero.
-or-
The resulting number of bytes is greater than the maximum number that can be returned as an integer.
DecoderFallbackException A fallback occurred
-and-
DecoderFallback is set to DecoderExceptionFallback.

Examples

The following example demonstrates how to use the GetMaxCharCount method to return the maximum number of characters produced by decoding a specified number of bytes.

Public Sub Main()
    Const ByteCount As Long = 8
    
    Dim UTF8 As New UTF8Encoding
    Dim MaxCharCount As Long
    
    MaxCharCount = UTF8.GetMaxCharCount(ByteCount)
    
    Console.WriteLine "Maximum of {0} characters needed to decode {1} bytes.", MaxCharCount, ByteCount
    Console.ReadKey
End Sub

' This code produces the following output.
'
'   Maximum of 9 characters needed to decode 8 bytes.

See Also

Project CorLib Overview

Class UTF8Encoding Overview

GetCharsEx

GetString

GetCharCount

GetDecoder