This documentation is archived and is not being maintained.

UnicodeEncoding.GetByteCount Method (String)

.NET Framework 1.1

Calculates the number of bytes required to store the results of encoding the characters from a specified String.

[Visual Basic]
Overrides Overloads Public Function GetByteCount( _
   ByVal s As String _
) As Integer
public override int GetByteCount(
 string s
public: int GetByteCount(
 String* s
public override function GetByteCount(
   s : String
) : int;


The String to encode.

Return Value

The number of bytes required to encode the characters in s.


Exception Type Condition
ArgumentNullException s is a null reference (Nothing in Visual Basic).
ArgumentException Return value is greater than MaxValue.


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


[Visual Basic, C#, C++] The following example demonstrates how to use the GetByteCount method to return the number of bytes required to encode the String chars using a UnicodeEncoding.

[Visual Basic] 
Imports System
Imports System.Text

Class UnicodeEncodingExample
   Public Shared Sub Main()
      Dim chars As String = "Unicode Encoding Example"
      Dim uni As New UnicodeEncoding()
      Dim byteCount As Integer = uni.GetByteCount(chars)
      Console.WriteLine("{0} bytes needed to encode string.", byteCount)
   End Sub 'Main
End Class 'UnicodeEncodingExample

using System;
using System.Text;

class UnicodeEncodingExample {
    public static void Main() {
        String chars = "Unicode Encoding Example";

        UnicodeEncoding Unicode = new UnicodeEncoding();
        int byteCount = Unicode.GetByteCount(chars);
            "{0} bytes needed to encode string.", byteCount

#using <mscorlib.dll>
using namespace System;
using namespace System::Text;

int main()
   String * chars = S"Unicode Encoding Example";

   UnicodeEncoding* Unicode = new UnicodeEncoding();
   int byteCount = Unicode -> GetByteCount(chars);
   Console::WriteLine(S"{0} bytes needed to encode string.", __box(byteCount));

[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.


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

UnicodeEncoding Class | UnicodeEncoding Members | System.Text Namespace | UnicodeEncoding.GetByteCount Overload List