This documentation is archived and is not being maintained.

UTF8Encoding.GetMaxByteCount Method

Calculates the maximum number of bytes required to encode a specified number of characters.

[Visual Basic]
Overrides Public Function GetMaxByteCount( _
   ByVal charCount As Integer _
) As Integer
[C#]
public override int GetMaxByteCount(
 int charCount
);
[C++]
public: int GetMaxByteCount(
 int charCount
);
[JScript]
public override function GetMaxByteCount(
   charCount : int
) : int;

Parameters

charCount
The number of characters to encode.

Return Value

The maximum number of bytes required to encode charCount number of characters.

Exceptions

Exception Type Condition
ArgumentOutOfRangeException charCount is less than zero.

-or-

charCount is too large to store as type Int32.

Remarks

Use GetByteCount to calculate exactly, or GetMaxByteCount to calculate at most, the array size required by the GetBytes method to store encoded characters.

Example

[Visual Basic, C#, C++] The following example demonstrates how to use the GetMaxByteCount method to return the maximum number of bytes required to encode a specified number of characters stored in the variable charCount.

[Visual Basic] 
Imports System
Imports System.Text

Class UTF8EncodingExample
    
    Public Shared Sub Main()
        Dim utf8 As New UTF8Encoding()
        Dim charCount As Integer = 2
        Dim maxByteCount As Integer = utf8.GetMaxByteCount(charCount)
        Console.WriteLine( _
            "Maximum of {0} bytes needed to encode {1} characters.", _
            maxByteCount, _
            charCount _
        )
    End Sub 'Main
End Class 'UTF8EncodingExample

[C#] 
using System;
using System.Text;

class UTF8EncodingExample {
    public static void Main() {
        UTF8Encoding utf8 = new UTF8Encoding();
        int charCount = 2;
        int maxByteCount = utf8.GetMaxByteCount(charCount);
        Console.WriteLine(
            "Maximum of {0} bytes needed to encode {1} characters.",
            maxByteCount,
            charCount
        );
    }
}

[C++] 
#using <mscorlib.dll>
using namespace System;
using namespace System::Text;

int main() {
   UTF8Encoding* utf8 = new UTF8Encoding();
   int charCount = 2;
   int maxByteCount = utf8->GetMaxByteCount(charCount);
   Console::WriteLine(S"Maximum of {0} bytes needed to encode {1} characters.", 
      __box(maxByteCount), __box(charCount));
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

See Also

UTF8Encoding Class | UTF8Encoding Members | System.Text Namespace | GetBytes | GetBytes

Show: