Ler em inglês

Compartilhar via


Convert.ToString Método

Definição

Converte o valor especificado na representação de cadeia de caracteres equivalente.

Sobrecargas

ToString(Int32, IFormatProvider)

Converte o valor do inteiro com sinal de 32 bits especificado em sua representação de cadeia de caracteres equivalente usando as informações de formatação específicas da cultura especificadas.

ToString(Int16, Int32)

Converte o valor de um inteiro com sinal de 16 bits em sua representação de cadeia de caracteres equivalente em uma base especificada.

ToString(DateTime, IFormatProvider)

Converte o valor do DateTime especificado na representação de cadeia de caracteres equivalente usando as informações de formatação específicas da cultura determinadas.

ToString(Double, IFormatProvider)

Converte o valor do número de ponto flutuante de precisão dupla especificado em sua representação de cadeia de caracteres equivalente.

ToString(Decimal, IFormatProvider)

Converte o valor do número decimal especificado na representação de cadeia de caracteres equivalente usando as informações de formatação específicas da cultura especificadas.

ToString(Int32, Int32)

Converte o valor de um inteiro com sinal de 32 bits na representação de cadeia de caracteres equivalente a ele em uma base especificada.

ToString(Int16, IFormatProvider)

Converte o valor do inteiro com sinal de 16 bits especificado em sua representação de cadeia de caracteres equivalente usando as informações de formatação específicas da cultura especificadas.

ToString(Int64, IFormatProvider)

Converte o valor do inteiro com sinal de 64 bits especificado na representação de cadeia de caracteres equivalente, usando as informações de formatação específicas à cultura especificadas.

ToString(Single, IFormatProvider)

Converte o valor do número de ponto flutuante de precisão simples em sua representação de cadeia de caracteres equivalente, usando as informações de formatação específicas da cultura.

ToString(Object, IFormatProvider)

Converte o valor do objeto especificado na representação de cadeia de caracteres equivalente usando as informações de formatação específicas da cultura especificadas.

ToString(SByte, IFormatProvider)

Converte o valor do inteiro com sinal de 8 bits especificado em sua representação de cadeia de caracteres equivalente, usando as informações de formatação específicas à cultura especificadas.

ToString(String, IFormatProvider)

Retorna a instância de cadeia de caracteres especificada; nenhuma conversão real é executada.

ToString(UInt16, IFormatProvider)

Converte o valor do inteiro sem sinal de 16 bits especificado na representação de cadeia de caracteres equivalente, usando as informações de formatação específicas à cultura especificadas.

ToString(UInt32, IFormatProvider)

Converte o valor do inteiro sem sinal de 32 bits especificado na representação de cadeia de caracteres equivalente, usando as informações de formatação específicas à cultura especificadas.

ToString(UInt64, IFormatProvider)

Converte o valor do inteiro sem sinal de 64 bits especificado na representação de cadeia de caracteres equivalente, usando as informações de formatação específicas à cultura especificadas.

ToString(Char, IFormatProvider)

Converte o valor do caractere Unicode especificado em sua representação de cadeia de caracteres equivalente, usando as informações de formatação específicas da cultura especificadas.

ToString(Int64, Int32)

Converte o valor de um inteiro com sinal de 64 bits na representação de cadeia de caracteres equivalente a ele em uma base especificada.

ToString(Byte, Int32)

Converte o valor de um inteiro sem sinal de 8 bits em sua representação de cadeia de caracteres equivalente de uma base especificada.

ToString(Boolean, IFormatProvider)

Converte o valor booliano especificado na representação de cadeia de caracteres equivalente.

ToString(Byte, IFormatProvider)

Converte o valor do inteiro sem sinal de 8 bits especificado em sua representação de cadeia de caracteres equivalente, usando as informações de formatação específicas da cultura especificadas.

ToString(Boolean)

Converte o valor booliano especificado na representação de cadeia de caracteres equivalente.

ToString(Byte)

Converte o valor do inteiro sem sinal de 8 bits especificado na representação de cadeia de caracteres equivalente.

ToString(Char)

Converte o valor do caractere Unicode especificado na representação de cadeia de caracteres equivalente.

ToString(DateTime)

Converte o valor do DateTime especificado na representação de cadeia de caracteres equivalente.

ToString(Double)

Converte o valor do número de ponto flutuante de precisão dupla especificado em sua representação de cadeia de caracteres equivalente.

ToString(Int16)

Converte o valor do inteiro com sinal de 16 bits especificado em sua representação de cadeia de caracteres equivalente.

ToString(Int32)

Converte o valor do inteiro com sinal de 32 bits especificado em sua representação de cadeia de caracteres equivalente.

ToString(Decimal)

Converte o valor do número decimal especificado na representação de cadeia de caracteres equivalente.

ToString(Object)

Converte o valor do objeto especificado na representação de cadeia de caracteres equivalente.

ToString(SByte)

Converte o valor do inteiro com sinal de 8 bits especificado em sua representação de cadeia de caracteres equivalente.

ToString(Single)

Converte o valor do número de ponto flutuante de precisão simples especificado em sua representação de cadeia de caracteres equivalente.

ToString(String)

Retorna a instância de cadeia de caracteres especificada; nenhuma conversão real é executada.

ToString(UInt16)

Converte o valor do inteiro sem sinal de 16 bits especificado em uma representação de cadeia de caracteres equivalente.

ToString(UInt32)

Converte o valor do inteiro sem sinal de 32 bits especificado na representação de cadeia de caracteres equivalente.

ToString(UInt64)

Converte o valor do inteiro sem sinal de 64 bits especificado na representação de cadeia de caracteres equivalente.

ToString(Int64)

Converte o valor do inteiro com sinal de 64 bits especificado em sua representação de cadeia de caracteres equivalente.

ToString(Int32, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do inteiro com sinal de 32 bits especificado em sua representação de cadeia de caracteres equivalente usando as informações de formatação específicas da cultura especificadas.

C#
public static string ToString (int value, IFormatProvider provider);
C#
public static string ToString (int value, IFormatProvider? provider);

Parâmetros

value
Int32

O inteiro com sinal de 32 bits a converter.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir define uma classe NumberFormatInfo personalizada que define o sinal de subtração como a cadeia de caracteres "~" e o sinal de adição como a cadeia de caracteres "!". Em seguida, ele chama o ToString(Int32, IFormatProvider) método para converter cada elemento em uma matriz de inteiros em sua representação de cadeia de caracteres equivalente. A conversão usa a cultura invariável, bem como o objeto NumberFormatInfo personalizado.

C#
int[] numbers = { Int32.MinValue, Int32.MaxValue};
System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
nfi.NegativeSign = "~";
nfi.PositiveSign = "!";

foreach (int number in numbers)
   Console.WriteLine("{0,-12}  -->  {1,12}",
                     Convert.ToString(number, System.Globalization.CultureInfo.InvariantCulture),
                     Convert.ToString(number, nfi));
// The example displays the following output:
//       -2147483648  -->  ~2147483648
//       2147483647  -->  2147483647

Comentários

Essa implementação é idêntica a Int32.ToString(IFormatProvider).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Int16, Int32)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor de um inteiro com sinal de 16 bits em sua representação de cadeia de caracteres equivalente em uma base especificada.

C#
public static string ToString (short value, int toBase);

Parâmetros

value
Int16

O inteiro assinado de 16 bits a ser convertido.

toBase
Int32

A base do valor de retorno, que deve ser 2, 8, 10 ou 16.

Retornos

A representação da cadeia de caracteres de value na base toBase.

Exceções

toBase não é 2, 8, 10 ou 16.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de inteiros com sinal de 16 bits em suas representações de cadeia de caracteres binárias, octais, decimais e hexadecimal equivalentes.

C#
int[] bases = { 2, 8, 10, 16};
short[] numbers = { Int16.MinValue, -13621, -18, 12, 19142, Int16.MaxValue };

foreach (int baseValue in bases)
{
   Console.WriteLine("Base {0} conversion:", baseValue);
   foreach (short number in numbers)
   {
      Console.WriteLine("   {0,-8}  -->  0x{1}",
                        number, Convert.ToString(number, baseValue));
   }
}
// The example displays the following output:
//       Base 2 conversion:
//          -32768    -->  0x1000000000000000
//          -13621    -->  0x1100101011001011
//          -18       -->  0x1111111111101110
//          12        -->  0x1100
//          19142     -->  0x100101011000110
//          32767     -->  0x111111111111111
//       Base 8 conversion:
//          -32768    -->  0x100000
//          -13621    -->  0x145313
//          -18       -->  0x177756
//          12        -->  0x14
//          19142     -->  0x45306
//          32767     -->  0x77777
//       Base 10 conversion:
//          -32768    -->  0x-32768
//          -13621    -->  0x-13621
//          -18       -->  0x-18
//          12        -->  0x12
//          19142     -->  0x19142
//          32767     -->  0x32767
//       Base 16 conversion:
//          -32768    -->  0x8000
//          -13621    -->  0xcacb
//          -18       -->  0xffee
//          12        -->  0xc
//          19142     -->  0x4ac6
//          32767     -->  0x7fff

Comentários

Se value for positivo e toBase for 2, 8 ou 16, a cadeia de caracteres retornada usará representação de sinal e magnitude. Se value for negativo e toBase for 2, 8 ou 16, a cadeia de caracteres retornada usará a representação complementar de dois. Isso significa que o bit de alta ordem do byte de alta ordem (bit 15) é interpretado como o bit de sinal. Se o ToString(Int16, Int32) método for chamado para criar uma cadeia de caracteres que posteriormente será convertida em um número, um método correspondente que pressupõe que uma representação numérica semelhante deve ser chamada para executar a conversão. Esses métodos incluem Convert.ToInt16(String, Int32) e Int16.Parse(String, NumberStyles).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(DateTime, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do DateTime especificado na representação de cadeia de caracteres equivalente usando as informações de formatação específicas da cultura determinadas.

C#
public static string ToString (DateTime value, IFormatProvider provider);
C#
public static string ToString (DateTime value, IFormatProvider? provider);

Parâmetros

value
DateTime

O valor de data e tempo a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte um DateTime valor em sua representação de cadeia de caracteres equivalente em oito culturas diferentes.

C#
// Specify the date to be formatted using various cultures.
DateTime tDate = new DateTime(2010, 4, 15, 20, 30, 40, 333);
// Specify the cultures.
string[] cultureNames = { "en-US", "es-AR", "fr-FR", "hi-IN",
                          "ja-JP", "nl-NL", "ru-RU", "ur-PK" };

Console.WriteLine("Converting the date {0}: ",
                  Convert.ToString(tDate,
                          System.Globalization.CultureInfo.InvariantCulture));

foreach (string cultureName in cultureNames)
{
   System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName);
   string dateString = Convert.ToString(tDate, culture);
   Console.WriteLine("   {0}:  {1,-12}",
                     culture.Name, dateString);
}
// The example displays the following output:
//       Converting the date 04/15/2010 20:30:40:
//          en-US:  4/15/2010 8:30:40 PM
//          es-AR:  15/04/2010 08:30:40 p.m.
//          fr-FR:  15/04/2010 20:30:40
//          hi-IN:  15-04-2010 20:30:40
//          ja-JP:  2010/04/15 20:30:40
//          nl-NL:  15-4-2010 20:30:40
//          ru-RU:  15.04.2010 20:30:40
//          ur-PK:  15/04/2010 8:30:40 PM

Comentários

Essa implementação é idêntica a DateTime.ToString(IFormatProvider).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Double, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do número de ponto flutuante de precisão dupla especificado em sua representação de cadeia de caracteres equivalente.

C#
public static string ToString (double value, IFormatProvider provider);
C#
public static string ToString (double value, IFormatProvider? provider);

Parâmetros

value
Double

O número de ponto flutuante de precisão dupla a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de Double valores em sua representação de cadeia de caracteres equivalente em quatro culturas diferentes.

C#
// Define an array of numbers to display.
double[] numbers = { -1.5345e16, -123.4321, 19092.123, 1.1734231911290e16 };
// Define the culture names used to display them.
string[] cultureNames = { "en-US", "fr-FR", "ja-JP", "ru-RU" };

foreach (double number in numbers)
{
   Console.WriteLine("{0}:", Convert.ToString(number,
                             System.Globalization.CultureInfo.InvariantCulture));
   foreach (string cultureName in cultureNames)
   {
      System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName);
      Console.WriteLine("   {0}: {1,20}",
                        culture.Name, Convert.ToString(number, culture));
   }
   Console.WriteLine();
}
// The example displays the following output:
//    -1.5345E+16:
//       en-US:          -1.5345E+16
//       fr-FR:          -1,5345E+16
//       ja-JP:          -1.5345E+16
//       ru-RU:          -1,5345E+16
//
//    -123.4321:
//       en-US:            -123.4321
//       fr-FR:            -123,4321
//       ja-JP:            -123.4321
//       ru-RU:            -123,4321
//
//    19092.123:
//       en-US:            19092.123
//       fr-FR:            19092,123
//       ja-JP:            19092.123
//       ru-RU:            19092,123
//
//    1.173423191129E+16:
//       en-US:   1.173423191129E+16
//       fr-FR:   1,173423191129E+16
//       ja-JP:   1.173423191129E+16
//       ru-RU:   1,173423191129E+16

Comentários

Essa implementação é idêntica a Double.ToString(IFormatProvider)

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Decimal, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do número decimal especificado na representação de cadeia de caracteres equivalente usando as informações de formatação específicas da cultura especificadas.

C#
public static string ToString (decimal value, IFormatProvider provider);
C#
public static string ToString (decimal value, IFormatProvider? provider);

Parâmetros

value
Decimal

O número decimal a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de Decimal valores em sua representação de cadeia de caracteres equivalente em quatro culturas diferentes.

C#
// Define an array of numbers to display.
decimal[] numbers = { 1734231911290.16m, -17394.32921m,
                      3193.23m, 98012368321.684m };
// Define the culture names used to display them.
string[] cultureNames = { "en-US", "fr-FR", "ja-JP", "ru-RU" };

foreach (decimal number in numbers)
{
   Console.WriteLine("{0}:", Convert.ToString(number,
                             System.Globalization.CultureInfo.InvariantCulture));
   foreach (string cultureName in cultureNames)
   {
      System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName);
      Console.WriteLine("   {0}: {1,20}",
                        culture.Name, Convert.ToString(number, culture));
   }
   Console.WriteLine();
}
// The example displays the following output:
//    1734231911290.16:
//       en-US:     1734231911290.16
//       fr-FR:     1734231911290,16
//       ja-JP:     1734231911290.16
//       ru-RU:     1734231911290,16
//
//    -17394.32921:
//       en-US:         -17394.32921
//       fr-FR:         -17394,32921
//       ja-JP:         -17394.32921
//       ru-RU:         -17394,32921
//
//    3193.23:
//       en-US:              3193.23
//       fr-FR:              3193,23
//       ja-JP:              3193.23
//       ru-RU:              3193,23
//
//    98012368321.684:
//       en-US:      98012368321.684
//       fr-FR:      98012368321,684
//       ja-JP:      98012368321.684
//       ru-RU:      98012368321,684

Comentários

Essa implementação é idêntica a Decimal.ToString(IFormatProvider).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Int32, Int32)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor de um inteiro com sinal de 32 bits na representação de cadeia de caracteres equivalente a ele em uma base especificada.

C#
public static string ToString (int value, int toBase);

Parâmetros

value
Int32

O inteiro com sinal de 32 bits a converter.

toBase
Int32

A base do valor de retorno, que deve ser 2, 8, 10 ou 16.

Retornos

A representação da cadeia de caracteres de value na base toBase.

Exceções

toBase não é 2, 8, 10 ou 16.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de inteiros em suas representações de cadeia de caracteres binárias, hexadecimal, decimal e hexadecimal equivalentes.

C#
int[] bases = { 2, 8, 10, 16};
int[] numbers = { Int32.MinValue, -19327543, -13621, -18, 12,
                             19142, Int32.MaxValue };

foreach (int baseValue in bases)
{
   Console.WriteLine("Base {0} conversion:", baseValue);
   foreach (int number in numbers)
   {
      Console.WriteLine("   {0,-15}  -->  0x{1}",
                        number, Convert.ToString(number, baseValue));
   }
}
// The example displays the following output:
//    Base 2 conversion:
//       -2147483648      -->  0x10000000000000000000000000000000
//       -19327543        -->  0x11111110110110010001010111001001
//       -13621           -->  0x11111111111111111100101011001011
//       -18              -->  0x11111111111111111111111111101110
//       12               -->  0x1100
//       19142            -->  0x100101011000110
//       2147483647       -->  0x1111111111111111111111111111111
//    Base 8 conversion:
//       -2147483648      -->  0x20000000000
//       -19327543        -->  0x37666212711
//       -13621           -->  0x37777745313
//       -18              -->  0x37777777756
//       12               -->  0x14
//       19142            -->  0x45306
//       2147483647       -->  0x17777777777
//    Base 10 conversion:
//       -2147483648      -->  0x-2147483648
//       -19327543        -->  0x-19327543
//       -13621           -->  0x-13621
//       -18              -->  0x-18
//       12               -->  0x12
//       19142            -->  0x19142
//       2147483647       -->  0x2147483647
//    Base 16 conversion:
//       -2147483648      -->  0x80000000
//       -19327543        -->  0xfed915c9
//       -13621           -->  0xffffcacb
//       -18              -->  0xffffffee
//       12               -->  0xc
//       19142            -->  0x4ac6
//       2147483647       -->  0x7fffffff

Comentários

Se value for positivo e toBase for 2, 8 ou 16, a cadeia de caracteres retornada usará a representação de sinal e magnitude. Se value for negativo e toBase for 2, 8 ou 16, a cadeia de caracteres retornada usará a representação complementar de dois. Isso significa que o bit de ordem alta do byte de ordem mais alta (bit 31) é interpretado como o bit de sinal. Se o ToString(Int32, Int32) método for chamado para criar uma cadeia de caracteres que posteriormente será convertida de volta em um número, um método correspondente que pressupõe que uma representação numérica semelhante deve ser chamada para executar a conversão. Esses métodos incluem Convert.ToInt32(String, Int32) e Int32.Parse(String, NumberStyles).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Int16, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do inteiro com sinal de 16 bits especificado em sua representação de cadeia de caracteres equivalente usando as informações de formatação específicas da cultura especificadas.

C#
public static string ToString (short value, IFormatProvider provider);
C#
public static string ToString (short value, IFormatProvider? provider);

Parâmetros

value
Int16

O inteiro assinado de 16 bits a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir define uma classe NumberFormatInfo personalizada que define o sinal de subtração como a cadeia de caracteres "~" e o sinal de adição como a cadeia de caracteres "!". Em seguida, ele chama o ToString(Int16, IFormatProvider) método para converter cada elemento em uma matriz de inteiros de 16 bits em sua representação de cadeia de caracteres equivalente. A conversão usa a cultura invariável, bem como o objeto NumberFormatInfo personalizado.

C#
short[] numbers = { Int16.MinValue, Int16.MaxValue};
System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
nfi.NegativeSign = "~";
nfi.PositiveSign = "!";

foreach (short number in numbers)
   Console.WriteLine("{0,-8}  -->  {1,8}",
                     Convert.ToString(number, System.Globalization.CultureInfo.InvariantCulture),
                     Convert.ToString(number, nfi));
// The example displays the following output:
//       -32768    -->    ~32768
//       32767     -->     32767

Comentários

Essa implementação é idêntica a Int16.ToString(IFormatProvider).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Int64, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do inteiro com sinal de 64 bits especificado na representação de cadeia de caracteres equivalente, usando as informações de formatação específicas à cultura especificadas.

C#
public static string ToString (long value, IFormatProvider provider);
C#
public static string ToString (long value, IFormatProvider? provider);

Parâmetros

value
Int64

O inteiro com sinal de 64 bits a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir define uma classe NumberFormatInfo personalizada que define o sinal de subtração como a cadeia de caracteres "~" e o sinal de adição como a cadeia de caracteres "!". Em seguida, ele chama o ToString(Int64, IFormatProvider) método para converter cada elemento em uma matriz de inteiros longa em sua representação de cadeia de caracteres equivalente. A conversão usa a cultura invariável, bem como o objeto NumberFormatInfo personalizado.

C#
long[] numbers = { ((long) Int32.MinValue) * 2, ((long) Int32.MaxValue) * 2};
System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
nfi.NegativeSign = "~";
nfi.PositiveSign = "!";

foreach (long number in numbers)
   Console.WriteLine("{0,-12}  -->  {1,12}",
                     Convert.ToString(number, System.Globalization.CultureInfo.InvariantCulture),
                     Convert.ToString(number, nfi));
// The example displays the following output:
//       -4294967296  -->  ~4294967296
//       4294967294  -->  4294967294

Comentários

Essa implementação é idêntica a Int64.ToString(IFormatProvider).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Single, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do número de ponto flutuante de precisão simples em sua representação de cadeia de caracteres equivalente, usando as informações de formatação específicas da cultura.

C#
public static string ToString (float value, IFormatProvider provider);
C#
public static string ToString (float value, IFormatProvider? provider);

Parâmetros

value
Single

O número de ponto flutuante de precisão simples a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de Single valores em sua representação de cadeia de caracteres equivalente em quatro culturas diferentes.

C#
// Define an array of numbers to display.
float[] numbers = { -1.5345e16f, -123.4321f, 19092.123f, 1.1734231911290e16f };
// Define the culture names used to display them.
string[] cultureNames = { "en-US", "fr-FR", "ja-JP", "ru-RU" };

foreach (float number in numbers)
{
   Console.WriteLine("{0}:", Convert.ToString(number,
                             System.Globalization.CultureInfo.InvariantCulture));
   foreach (string cultureName in cultureNames)
   {
      System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName);
      Console.WriteLine("   {0}: {1,20}",
                        culture.Name, Convert.ToString(number, culture));
   }
   Console.WriteLine();
}
// The example displays the following output:
//    -1.5345E+16:
//       en-US:          -1.5345E+16
//       fr-FR:          -1,5345E+16
//       ja-JP:          -1.5345E+16
//       ru-RU:          -1,5345E+16
//
//    -123.4321:
//       en-US:            -123.4321
//       fr-FR:            -123,4321
//       ja-JP:            -123.4321
//       ru-RU:            -123,4321
//
//    19092.123:
//       en-US:            19092.123
//       fr-FR:            19092,123
//       ja-JP:            19092.123
//       ru-RU:            19092,123
//
//    1.173423191129E+16:
//       en-US:   1.173423191129E+16
//       fr-FR:   1,173423191129E+16
//       ja-JP:   1.173423191129E+16
//       ru-RU:   1,173423191129E+16

Comentários

Essa implementação é idêntica a Single.ToString(IFormatProvider).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Object, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do objeto especificado na representação de cadeia de caracteres equivalente usando as informações de formatação específicas da cultura especificadas.

C#
public static string ToString (object value, IFormatProvider provider);
C#
public static string? ToString (object? value, IFormatProvider? provider);

Parâmetros

value
Object

Um objeto que fornece o valor a ser convertido ou null.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação de cadeia de caracteres de value, ou Empty se value for um objeto cujo valor é null. Se value for null, o método retornará null.

Exemplos

O exemplo a seguir define uma Temperature classe que substitui o Object.ToString método , mas não implementa a IConvertible interface . O exemplo ilustra como as chamadas para o Convert.ToString(Object, IFormatProvider) método, por sua vez, chamam o Temperature.ToString método .

C#
using System;

public class Temperature
{
   private decimal m_Temp;

   public Temperature(decimal temperature)
   {
      this.m_Temp = temperature;
   }

   public decimal Celsius
   {
      get { return this.m_Temp; }
   }

   public decimal Kelvin
   {
      get { return this.m_Temp + 273.15m; }
   }

   public decimal Fahrenheit
   {
      get { return Math.Round((decimal) (this.m_Temp * 9 / 5 + 32), 2); }
   }

   public override string ToString()
   {
      return m_Temp.ToString("N2") + " °C";
   }
}

public class Example
{
   public static void Main()
   {
      Temperature cold = new Temperature(-40);
      Temperature freezing = new Temperature(0);
      Temperature boiling = new Temperature(100);

      Console.WriteLine(Convert.ToString(cold, null));
      Console.WriteLine(Convert.ToString(freezing, null));
      Console.WriteLine(Convert.ToString(boiling, null));
   }
}
// The example dosplays the following output:
//       -40.00 °C
//       0.00 °C
//       100.00 °C

O exemplo a seguir define uma Temperature classe que implementa a IFormattable interface , mas não implementa a IConvertible interface . Sua IFormattable.ToString implementação representa o Temperature valor em Celsius, Fahrenheit ou Kelvin, dependendo da cadeia de caracteres de formato. O exemplo também define uma TemperatureProvider classe que implementa e fornece uma cadeia de caracteres IFormatProvider de formato gerada aleatoriamente que é usada pela IFormattable implementação da Temperature classe .

C#
using System;

public class Temperature : IFormattable
{
   private decimal m_Temp;

   public Temperature(decimal temperature)
   {
      this.m_Temp = temperature;
   }

   public decimal Celsius
   { get { return this.m_Temp; } }

   public decimal Kelvin
   { get { return this.m_Temp + 273.15m; } }

   public decimal Fahrenheit
   {  get { return Math.Round(this.m_Temp * 9m / 5m + 32m, 2); } }

   public override String ToString()
   {
      return ToString("G", null);
   }

   public String ToString(String fmt, IFormatProvider provider)
   {
      TemperatureProvider formatter = null;
      if (provider != null)
         formatter = provider.GetFormat(typeof(TemperatureProvider))
                                       as TemperatureProvider;

      if (String.IsNullOrWhiteSpace(fmt)) {
         if (formatter != null)
            fmt = formatter.Format;
         else
            fmt = "G";
      }

      switch (fmt.ToUpper()) {
         case "G":
         case "C":
            return m_Temp.ToString("N2") + " °C";
         case "F":
            return Fahrenheit.ToString("N2") + " °F";
         case "K":
            return Kelvin.ToString("N2") + " K";
         default:
            throw new FormatException(String.Format("'{0}' is not a valid format specifier.", fmt));
      }
   }
}

public class TemperatureProvider : IFormatProvider
{
   private String[] fmtStrings = { "C", "G", "F", "K" };
   private Random rnd = new Random();

   public Object GetFormat(Type formatType)
   {
      return this;
   }

   public String Format
   { get { return fmtStrings[rnd.Next(0, fmtStrings.Length)]; } }
}

public class Example
{
   public static void Main()
   {
      Temperature cold = new Temperature (-40);
      Temperature freezing = new Temperature (0);
      Temperature boiling = new Temperature (100);

      TemperatureProvider tp = new TemperatureProvider();

      Console.WriteLine(Convert.ToString(cold, tp));
      Console.WriteLine(Convert.ToString(freezing, tp));
      Console.WriteLine(Convert.ToString(boiling, tp));
   }
}
// The example displays output like the following:
//       -40.00 °C
//       273.15 K
//       100.00 °C

Comentários

Se o value parâmetro implementar a IConvertible interface , o método chamará a IConvertible.ToString(IFormatProvider) implementação de value. Caso contrário, se o value parâmetro implementar a IFormattable interface , o método chamará sua IFormattable.ToString(String, IFormatProvider) implementação. Se value não implementar nenhuma interface, o método chamará o value método do ToString() parâmetro e o provider parâmetro será ignorado.

O provider parâmetro será usado se o value parâmetro implementar a IConvertible interface ou IFormattable . O uso mais comum do provider parâmetro é especificar informações específicas da cultura usadas na conversão de value. Por exemplo, se o value parâmetro for um número decimal negativo, o provider parâmetro poderá fornecer informações específicas da cultura sobre a notação usada para o sinal negativo e o separador decimal. O segundo exemplo na próxima seção ilustra um provedor de formato que não fornece informações de formatação sensíveis à cultura.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(SByte, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Importante

Esta API não está em conformidade com CLS.

Converte o valor do inteiro com sinal de 8 bits especificado em sua representação de cadeia de caracteres equivalente, usando as informações de formatação específicas à cultura especificadas.

C#
[System.CLSCompliant(false)]
public static string ToString (sbyte value, IFormatProvider provider);
C#
[System.CLSCompliant(false)]
public static string ToString (sbyte value, IFormatProvider? provider);

Parâmetros

value
SByte

O inteiro com sinal de 8 bits a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação da cadeia de caracteres de value.

Atributos

Exemplos

O exemplo a seguir define uma classe NumberFormatInfo personalizada que define o sinal de subtração como a cadeia de caracteres "~" e o sinal de adição como a cadeia de caracteres "!". Em seguida, ele chama o Convert.ToString(SByte, IFormatProvider) método para converter cada elemento na matriz de bytes com sinal em sua representação de cadeia de caracteres equivalente. A conversão usa a cultura invariável, bem como o objeto NumberFormatInfo personalizado.

C#
sbyte[] numbers = { SByte.MinValue, -12, 17, SByte.MaxValue};
System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
nfi.NegativeSign = "~";
nfi.PositiveSign = "!";
foreach (sbyte number in numbers)
   Console.WriteLine(Convert.ToString(number, nfi));
// The example displays the following output:
//       ~128
//       ~12
//       17
//       127

Comentários

Essa implementação é idêntica a SByte.ToString(IFormatProvider).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(String, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Retorna a instância de cadeia de caracteres especificada; nenhuma conversão real é executada.

C#
public static string? ToString (string? value, IFormatProvider? provider);
C#
public static string ToString (string value, IFormatProvider provider);

Parâmetros

value
String

A cadeia de caracteres a ser retornada.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura. Este parâmetro é ignorado.

Retornos

value é retornado inalterado.

Exemplos

O exemplo a seguir chama o ToString método com um String parâmetro . O método retorna o não modificado String sem referenciar o IFormatProvider objeto .

C#
// Example of Convert.ToString( non-numeric types, IFormatProvider ).
using System;
using System.Globalization;

// An instance of this class can be passed to methods that require
// an IFormatProvider.
public class DummyProvider : IFormatProvider
{
    // Normally, GetFormat returns an object of the requested type
    // (usually itself) if it is able; otherwise, it returns Nothing.
    public object GetFormat( Type argType )
    {
        // Here, the type of argType is displayed, and GetFormat
        // always returns Nothing.
        Console.Write( "{0,-40}", argType.ToString( ) );
        return null;
    }
}

class ConvertNonNumericProviderDemo
{
    static void Main( )
    {
        // Create an instance of the IFormatProvider.
        DummyProvider provider = new DummyProvider( );
        string converted;

        // Convert these values using DummyProvider.
        int      Int32A     = -252645135;
        double   DoubleA    = 61680.3855;
        object   ObjDouble  = (object)( -98765.4321 );
        DateTime DayTimeA   = new DateTime( 2001, 9, 11, 13, 45, 0 );

        bool     BoolA      = true;
        string   StringA    = "Qwerty";
        char     CharA      = '$';
        TimeSpan TSpanA     = new TimeSpan( 0, 18, 0 );
        object   ObjOther   = (object)provider;

        Console.WriteLine( "This example of " +
            "Convert.ToString( non-numeric, IFormatProvider ) \n" +
            "generates the following output. The provider type, " +
            "argument type, \nand argument value are displayed." );
        Console.WriteLine( "\nNote: The IFormatProvider object is " +
            "not called for Boolean, String, \nChar, TimeSpan, " +
            "and non-numeric Object." );

        // The format provider is called for these conversions.
        Console.WriteLine( );
        converted = Convert.ToString( Int32A, provider );
        Console.WriteLine( "int      {0}", converted );
        converted = Convert.ToString( DoubleA, provider );
        Console.WriteLine( "double   {0}", converted );
        converted = Convert.ToString( ObjDouble, provider );
        Console.WriteLine( "object   {0}", converted );
        converted = Convert.ToString( DayTimeA, provider );
        Console.WriteLine( "DateTime {0}", converted );

        // The format provider is not called for these conversions.
        Console.WriteLine( );
        converted = Convert.ToString( BoolA, provider );
        Console.WriteLine( "bool     {0}", converted );
        converted = Convert.ToString( StringA, provider );
        Console.WriteLine( "string   {0}", converted );
        converted = Convert.ToString( CharA, provider );
        Console.WriteLine( "char     {0}", converted );
        converted = Convert.ToString( TSpanA, provider );
        Console.WriteLine( "TimeSpan {0}", converted );
        converted = Convert.ToString( ObjOther, provider );
        Console.WriteLine( "object   {0}", converted );
    }
}

/*
This example of Convert.ToString( non-numeric, IFormatProvider )
generates the following output. The provider type, argument type,
and argument value are displayed.

Note: The IFormatProvider object is not called for Boolean, String,
Char, TimeSpan, and non-numeric Object.

System.Globalization.NumberFormatInfo   int      -252645135
System.Globalization.NumberFormatInfo   double   61680.3855
System.Globalization.NumberFormatInfo   object   -98765.4321
System.Globalization.DateTimeFormatInfo DateTime 9/11/2001 1:45:00 PM

bool     True
string   Qwerty
char     $
TimeSpan 00:18:00
object   DummyProvider

*/

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

ToString(UInt16, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Importante

Esta API não está em conformidade com CLS.

Converte o valor do inteiro sem sinal de 16 bits especificado na representação de cadeia de caracteres equivalente, usando as informações de formatação específicas à cultura especificadas.

C#
[System.CLSCompliant(false)]
public static string ToString (ushort value, IFormatProvider provider);
C#
[System.CLSCompliant(false)]
public static string ToString (ushort value, IFormatProvider? provider);

Parâmetros

value
UInt16

O inteiro não assinado de 16 bits a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação da cadeia de caracteres de value.

Atributos

Exemplos

O exemplo a seguir define uma classe NumberFormatInfo personalizada que define o sinal de subtração como a cadeia de caracteres "~" e o sinal de adição como a cadeia de caracteres "!". Em seguida, ele chama o ToString(UInt16, IFormatProvider) método para converter um valor inteiro sem sinal de 16 bits em sua representação de cadeia de caracteres equivalente. A conversão usa a cultura invariável e o objeto personalizado NumberFormatInfo . A saída indica que essas informações de formatação não são usadas, pois, por padrão, o especificador de formato "G" não inclui um sinal positivo com valores positivos.

C#
ushort number = UInt16.MaxValue;
System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
nfi.NegativeSign = "~";
nfi.PositiveSign = "!";

Console.WriteLine("{0,-6}  -->  {1,6}",
                  Convert.ToString(number, System.Globalization.CultureInfo.InvariantCulture),
                  Convert.ToString(number, nfi));
// The example displays the following output:
//       65535   -->   65535

Comentários

Essa implementação é idêntica a UInt16.ToString(IFormatProvider).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(UInt32, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Importante

Esta API não está em conformidade com CLS.

Converte o valor do inteiro sem sinal de 32 bits especificado na representação de cadeia de caracteres equivalente, usando as informações de formatação específicas à cultura especificadas.

C#
[System.CLSCompliant(false)]
public static string ToString (uint value, IFormatProvider provider);
C#
[System.CLSCompliant(false)]
public static string ToString (uint value, IFormatProvider? provider);

Parâmetros

value
UInt32

O inteiro sem sinal de 32 bits a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação da cadeia de caracteres de value.

Atributos

Exemplos

O exemplo a seguir define uma classe NumberFormatInfo personalizada que define o sinal de subtração como a cadeia de caracteres "~" e o sinal de adição como a cadeia de caracteres "!". Em seguida, ele chama o ToString(UInt32, IFormatProvider) método para converter um valor inteiro sem sinal em sua representação de cadeia de caracteres equivalente. A conversão usa a cultura invariável e o objeto personalizado NumberFormatInfo . A saída indica que essas informações de formatação não são usadas, pois, por padrão, o especificador de formato "G" não inclui um sinal positivo com valores positivos.

C#
uint number = UInt32.MaxValue;
System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
nfi.NegativeSign = "~";
nfi.PositiveSign = "!";

Console.WriteLine("{0,-8}  -->  {1,8}",
                  Convert.ToString(number, System.Globalization.CultureInfo.InvariantCulture),
                  Convert.ToString(number, nfi));
// The example displays the following output:
//       4294967295  -->  4294967295

Comentários

Essa implementação é idêntica a UInt32.ToString(IFormatProvider).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(UInt64, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Importante

Esta API não está em conformidade com CLS.

Converte o valor do inteiro sem sinal de 64 bits especificado na representação de cadeia de caracteres equivalente, usando as informações de formatação específicas à cultura especificadas.

C#
[System.CLSCompliant(false)]
public static string ToString (ulong value, IFormatProvider provider);
C#
[System.CLSCompliant(false)]
public static string ToString (ulong value, IFormatProvider? provider);

Parâmetros

value
UInt64

O inteiro sem sinal de 64 bits a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação da cadeia de caracteres de value.

Atributos

Exemplos

O exemplo a seguir define uma classe NumberFormatInfo personalizada que define o sinal de subtração como a cadeia de caracteres "~" e o sinal de adição como a cadeia de caracteres "!". Em seguida, ele chama o ToString(UInt64, IFormatProvider) método para converter um valor inteiro longo sem sinal em sua representação de cadeia de caracteres equivalente. A conversão usa a cultura invariável e o objeto personalizado NumberFormatInfo . A saída indica que essas informações de formatação não são usadas, pois, por padrão, o especificador de formato "G" não inclui um sinal positivo com valores positivos.

C#
ulong number = UInt64.MaxValue;
System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
nfi.NegativeSign = "~";
nfi.PositiveSign = "!";

Console.WriteLine("{0,-12}  -->  {1,12}",
                  Convert.ToString(number, System.Globalization.CultureInfo.InvariantCulture),
                  Convert.ToString(number, nfi));
// The example displays the following output:
//    18446744073709551615  -->  18446744073709551615

Comentários

Essa implementação é idêntica a UInt64.ToString(IFormatProvider).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Char, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do caractere Unicode especificado em sua representação de cadeia de caracteres equivalente, usando as informações de formatação específicas da cultura especificadas.

C#
public static string ToString (char value, IFormatProvider provider);
C#
public static string ToString (char value, IFormatProvider? provider);

Parâmetros

value
Char

O caractere Unicode a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura. Este parâmetro é ignorado.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte um Char valor em um String com o ToString método , usando um IFormatProvider objeto que exibe o tipo do provedor de formato para o qual ele é chamado. O exemplo mostra que o IFormatProvider objeto não é referenciado.

C#
// Example of Convert.ToString( non-numeric types, IFormatProvider ).
using System;
using System.Globalization;

// An instance of this class can be passed to methods that require
// an IFormatProvider.
public class DummyProvider : IFormatProvider
{
    // Normally, GetFormat returns an object of the requested type
    // (usually itself) if it is able; otherwise, it returns Nothing.
    public object GetFormat( Type argType )
    {
        // Here, the type of argType is displayed, and GetFormat
        // always returns Nothing.
        Console.Write( "{0,-40}", argType.ToString( ) );
        return null;
    }
}

class ConvertNonNumericProviderDemo
{
    static void Main( )
    {
        // Create an instance of the IFormatProvider.
        DummyProvider provider = new DummyProvider( );
        string converted;

        // Convert these values using DummyProvider.
        int      Int32A     = -252645135;
        double   DoubleA    = 61680.3855;
        object   ObjDouble  = (object)( -98765.4321 );
        DateTime DayTimeA   = new DateTime( 2001, 9, 11, 13, 45, 0 );

        bool     BoolA      = true;
        string   StringA    = "Qwerty";
        char     CharA      = '$';
        TimeSpan TSpanA     = new TimeSpan( 0, 18, 0 );
        object   ObjOther   = (object)provider;

        Console.WriteLine( "This example of " +
            "Convert.ToString( non-numeric, IFormatProvider ) \n" +
            "generates the following output. The provider type, " +
            "argument type, \nand argument value are displayed." );
        Console.WriteLine( "\nNote: The IFormatProvider object is " +
            "not called for Boolean, String, \nChar, TimeSpan, " +
            "and non-numeric Object." );

        // The format provider is called for these conversions.
        Console.WriteLine( );
        converted = Convert.ToString( Int32A, provider );
        Console.WriteLine( "int      {0}", converted );
        converted = Convert.ToString( DoubleA, provider );
        Console.WriteLine( "double   {0}", converted );
        converted = Convert.ToString( ObjDouble, provider );
        Console.WriteLine( "object   {0}", converted );
        converted = Convert.ToString( DayTimeA, provider );
        Console.WriteLine( "DateTime {0}", converted );

        // The format provider is not called for these conversions.
        Console.WriteLine( );
        converted = Convert.ToString( BoolA, provider );
        Console.WriteLine( "bool     {0}", converted );
        converted = Convert.ToString( StringA, provider );
        Console.WriteLine( "string   {0}", converted );
        converted = Convert.ToString( CharA, provider );
        Console.WriteLine( "char     {0}", converted );
        converted = Convert.ToString( TSpanA, provider );
        Console.WriteLine( "TimeSpan {0}", converted );
        converted = Convert.ToString( ObjOther, provider );
        Console.WriteLine( "object   {0}", converted );
    }
}

/*
This example of Convert.ToString( non-numeric, IFormatProvider )
generates the following output. The provider type, argument type,
and argument value are displayed.

Note: The IFormatProvider object is not called for Boolean, String,
Char, TimeSpan, and non-numeric Object.

System.Globalization.NumberFormatInfo   int      -252645135
System.Globalization.NumberFormatInfo   double   61680.3855
System.Globalization.NumberFormatInfo   object   -98765.4321
System.Globalization.DateTimeFormatInfo DateTime 9/11/2001 1:45:00 PM

bool     True
string   Qwerty
char     $
TimeSpan 00:18:00
object   DummyProvider

*/

Comentários

Essa implementação é idêntica a Char.ToString(). O parâmetro provider é ignorado.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Int64, Int32)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor de um inteiro com sinal de 64 bits na representação de cadeia de caracteres equivalente a ele em uma base especificada.

C#
public static string ToString (long value, int toBase);

Parâmetros

value
Int64

O inteiro com sinal de 64 bits a ser convertido.

toBase
Int32

A base do valor de retorno, que deve ser 2, 8, 10 ou 16.

Retornos

A representação da cadeia de caracteres de value na base toBase.

Exceções

toBase não é 2, 8, 10 ou 16.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de inteiros longa em suas representações de cadeia de caracteres binárias, hexadecimal, decimal e hexadecimal equivalentes.

C#
int[] bases = { 2, 8, 10, 16};
long[] numbers = { Int64.MinValue, -193275430, -13621, -18, 12,
                   1914206117, Int64.MaxValue };

foreach (int baseValue in bases)
{
   Console.WriteLine("Base {0} conversion:", baseValue);
   foreach (long number in numbers)
   {
      Console.WriteLine("   {0,-23}  -->  0x{1}",
                        number, Convert.ToString(number, baseValue));
   }
}
// The example displays the following output:
//    Base 2 conversion:
//       -9223372036854775808     -->  0x1000000000000000000000000000000000000000000000000000000000000000
//       -193275430               -->  0x1111111111111111111111111111111111110100011110101101100111011010
//       -13621                   -->  0x1111111111111111111111111111111111111111111111111100101011001011
//       -18                      -->  0x1111111111111111111111111111111111111111111111111111111111101110
//       12                       -->  0x1100
//       1914206117               -->  0x1110010000110000111011110100101
//       9223372036854775807      -->  0x111111111111111111111111111111111111111111111111111111111111111
//    Base 8 conversion:
//       -9223372036854775808     -->  0x1000000000000000000000
//       -193275430               -->  0x1777777777776436554732
//       -13621                   -->  0x1777777777777777745313
//       -18                      -->  0x1777777777777777777756
//       12                       -->  0x14
//       1914206117               -->  0x16206073645
//       9223372036854775807      -->  0x777777777777777777777
//    Base 10 conversion:
//       -9223372036854775808     -->  0x-9223372036854775808
//       -193275430               -->  0x-193275430
//       -13621                   -->  0x-13621
//       -18                      -->  0x-18
//       12                       -->  0x12
//       1914206117               -->  0x1914206117
//       9223372036854775807      -->  0x9223372036854775807
//    Base 16 conversion:
//       -9223372036854775808     -->  0x8000000000000000
//       -193275430               -->  0xfffffffff47ad9da
//       -13621                   -->  0xffffffffffffcacb
//       -18                      -->  0xffffffffffffffee
//       12                       -->  0xc
//       1914206117               -->  0x721877a5
//       9223372036854775807      -->  0x7fffffffffffffff

Comentários

Se value for positivo e toBase não for 10, a cadeia de caracteres retornada usará representação de sinal e magnitude. Se value for negativo e toBase não for 10, a cadeia de caracteres retornada usará a representação complementar de dois. Isso significa que o bit de ordem alta do byte de ordem mais alta (bit 63) é interpretado como o bit de sinal. Se o ToString(Int64, Int32) método for chamado para criar uma cadeia de caracteres que posteriormente será convertida em um número, um método correspondente que pressupõe que uma representação numérica semelhante deve ser chamada para executar a conversão. Esses métodos incluem Convert.ToInt64(String, Int32) e Int64.Parse(String, NumberStyles).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Byte, Int32)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor de um inteiro sem sinal de 8 bits em sua representação de cadeia de caracteres equivalente de uma base especificada.

C#
public static string ToString (byte value, int toBase);

Parâmetros

value
Byte

O inteiro sem sinal de 8 bits a ser convertido.

toBase
Int32

A base do valor de retorno, que deve ser 2, 8, 10 ou 16.

Retornos

A representação da cadeia de caracteres de value na base toBase.

Exceções

toBase não é 2, 8, 10 ou 16.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de bytes em suas representações de cadeia de caracteres binárias, hexadecimal, decimal e hexadecimal equivalentes.

C#
int[] bases = { 2, 8, 10, 16};
byte[] numbers = { Byte.MinValue, 12, 103, Byte.MaxValue};

foreach (int baseValue in bases)
{
   Console.WriteLine("Base {0} conversion:", baseValue);
   foreach (byte number in numbers)
   {
      Console.WriteLine("   {0,-5}  -->  0x{1}",
                        number, Convert.ToString(number, baseValue));
   }
}
// The example displays the following output:
//       Base 2 conversion:
//          0      -->  0x0
//          12     -->  0x1100
//          103    -->  0x1100111
//          255    -->  0x11111111
//       Base 8 conversion:
//          0      -->  0x0
//          12     -->  0x14
//          103    -->  0x147
//          255    -->  0x377
//       Base 10 conversion:
//          0      -->  0x0
//          12     -->  0x12
//          103    -->  0x103
//          255    -->  0x255
//       Base 16 conversion:
//          0      -->  0x0
//          12     -->  0xc
//          103    -->  0x67
//          255    -->  0xff

Comentários

Se toBase não for igual a 10, a cadeia de caracteres value retornada pelo Convert.ToString(Byte, Int32) método representa apenas por sua magnitude. Se o método for chamado para criar uma cadeia de caracteres que posteriormente será convertida em um número, um método correspondente que pressupõe que uma representação numérica somente de magnitude deve ser chamada para executar a conversão. Esses métodos incluem Convert.ToByte(String, Int32) ou Byte.Parse(String, NumberStyles).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Boolean, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor booliano especificado na representação de cadeia de caracteres equivalente.

C#
public static string ToString (bool value, IFormatProvider provider);
C#
public static string ToString (bool value, IFormatProvider? provider);

Parâmetros

value
Boolean

O valor booliano a ser convertido.

provider
IFormatProvider

Uma instância de um objeto. Este parâmetro é ignorado.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte um Boolean valor em um String com o ToString método , usando um IFormatProvider objeto que exibe o tipo do provedor de formato para o qual ele é chamado. O exemplo mostra que o IFormatProvider objeto não é referenciado.

C#
// Example of Convert.ToString( non-numeric types, IFormatProvider ).
using System;
using System.Globalization;

// An instance of this class can be passed to methods that require
// an IFormatProvider.
public class DummyProvider : IFormatProvider
{
    // Normally, GetFormat returns an object of the requested type
    // (usually itself) if it is able; otherwise, it returns Nothing.
    public object GetFormat( Type argType )
    {
        // Here, the type of argType is displayed, and GetFormat
        // always returns Nothing.
        Console.Write( "{0,-40}", argType.ToString( ) );
        return null;
    }
}

class ConvertNonNumericProviderDemo
{
    static void Main( )
    {
        // Create an instance of the IFormatProvider.
        DummyProvider provider = new DummyProvider( );
        string converted;

        // Convert these values using DummyProvider.
        int      Int32A     = -252645135;
        double   DoubleA    = 61680.3855;
        object   ObjDouble  = (object)( -98765.4321 );
        DateTime DayTimeA   = new DateTime( 2001, 9, 11, 13, 45, 0 );

        bool     BoolA      = true;
        string   StringA    = "Qwerty";
        char     CharA      = '$';
        TimeSpan TSpanA     = new TimeSpan( 0, 18, 0 );
        object   ObjOther   = (object)provider;

        Console.WriteLine( "This example of " +
            "Convert.ToString( non-numeric, IFormatProvider ) \n" +
            "generates the following output. The provider type, " +
            "argument type, \nand argument value are displayed." );
        Console.WriteLine( "\nNote: The IFormatProvider object is " +
            "not called for Boolean, String, \nChar, TimeSpan, " +
            "and non-numeric Object." );

        // The format provider is called for these conversions.
        Console.WriteLine( );
        converted = Convert.ToString( Int32A, provider );
        Console.WriteLine( "int      {0}", converted );
        converted = Convert.ToString( DoubleA, provider );
        Console.WriteLine( "double   {0}", converted );
        converted = Convert.ToString( ObjDouble, provider );
        Console.WriteLine( "object   {0}", converted );
        converted = Convert.ToString( DayTimeA, provider );
        Console.WriteLine( "DateTime {0}", converted );

        // The format provider is not called for these conversions.
        Console.WriteLine( );
        converted = Convert.ToString( BoolA, provider );
        Console.WriteLine( "bool     {0}", converted );
        converted = Convert.ToString( StringA, provider );
        Console.WriteLine( "string   {0}", converted );
        converted = Convert.ToString( CharA, provider );
        Console.WriteLine( "char     {0}", converted );
        converted = Convert.ToString( TSpanA, provider );
        Console.WriteLine( "TimeSpan {0}", converted );
        converted = Convert.ToString( ObjOther, provider );
        Console.WriteLine( "object   {0}", converted );
    }
}

/*
This example of Convert.ToString( non-numeric, IFormatProvider )
generates the following output. The provider type, argument type,
and argument value are displayed.

Note: The IFormatProvider object is not called for Boolean, String,
Char, TimeSpan, and non-numeric Object.

System.Globalization.NumberFormatInfo   int      -252645135
System.Globalization.NumberFormatInfo   double   61680.3855
System.Globalization.NumberFormatInfo   object   -98765.4321
System.Globalization.DateTimeFormatInfo DateTime 9/11/2001 1:45:00 PM

bool     True
string   Qwerty
char     $
TimeSpan 00:18:00
object   DummyProvider

*/

Comentários

Essa implementação é idêntica a Boolean.ToString. Ele retorna Boolean.TrueString para true valores e Boolean.FalseString para false valores.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Byte, IFormatProvider)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do inteiro sem sinal de 8 bits especificado em sua representação de cadeia de caracteres equivalente, usando as informações de formatação específicas da cultura especificadas.

C#
public static string ToString (byte value, IFormatProvider provider);
C#
public static string ToString (byte value, IFormatProvider? provider);

Parâmetros

value
Byte

O inteiro sem sinal de 8 bits a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de bytes sem sinal em sua representação de cadeia de caracteres equivalente usando as convenções de formatação das culturas en-US e fr-FR. Como o especificador "G" por padrão gera apenas dígitos decimais na representação de cadeia de caracteres de um valor de byte, o provider parâmetro não afeta a formatação da cadeia de caracteres retornada.

C#
byte[] numbers = { 12, 100, Byte.MaxValue };
// Define the culture names used to display them.
string[] cultureNames = { "en-US", "fr-FR" };

foreach (byte number in numbers)
{
   Console.WriteLine("{0}:", Convert.ToString(number,
                             System.Globalization.CultureInfo.InvariantCulture));
   foreach (string cultureName in cultureNames)
   {
      System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName);
      Console.WriteLine("   {0}: {1,20}",
                        culture.Name, Convert.ToString(number, culture));
   }
   Console.WriteLine();
}
// The example displays the following output:
//       12:
//          en-US:                   12
//          fr-FR:                   12
//
//       100:
//          en-US:                  100
//          fr-FR:                  100
//
//       255:
//          en-US:                  255
//          fr-FR:                  255

Comentários

Essa implementação é idêntica a Byte.ToString.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Boolean)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor booliano especificado na representação de cadeia de caracteres equivalente.

C#
public static string ToString (bool value);

Parâmetros

value
Boolean

O valor booliano a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir ilustra a conversão de um Boolean em um String, usando ToString. Ele também ilustra que a cadeia de caracteres retornada pela conversão é igual Boolean.TrueString a ou Boolean.FalseString.

C#
bool falseFlag = false;
bool trueFlag = true;

Console.WriteLine(Convert.ToString(falseFlag));
Console.WriteLine(Convert.ToString(falseFlag).Equals(Boolean.FalseString));
Console.WriteLine(Convert.ToString(trueFlag));
Console.WriteLine(Convert.ToString(trueFlag).Equals(Boolean.TrueString));
// The example displays the following output:
//       False
//       True
//       True
//       True

Comentários

Essa implementação é idêntica a Boolean.ToString. Ele retorna Boolean.TrueString para true valores e Boolean.FalseString para false valores.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Byte)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do inteiro sem sinal de 8 bits especificado na representação de cadeia de caracteres equivalente.

C#
public static string ToString (byte value);

Parâmetros

value
Byte

O inteiro sem sinal de 8 bits a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte cada valor em uma Byte matriz em uma cadeia de caracteres.

C#
using System;

public class Example
{
   public static void Main()
   {
      byte[] values = { Byte.MinValue, 12, 100, 179, Byte.MaxValue } ;

      foreach (var value in values)
         Console.WriteLine("{0,3} ({1}) --> {2}", value,
                           value.GetType().Name,
                           Convert.ToString(value));
   }
}
// The example displays the following output:
//       0 (Byte) --> 0
//      12 (Byte) --> 12
//     100 (Byte) --> 100
//     179 (Byte) --> 179
//     255 (Byte) --> 255

Comentários

Essa implementação é idêntica a Byte.ToString().

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Char)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do caractere Unicode especificado na representação de cadeia de caracteres equivalente.

C#
public static string ToString (char value);

Parâmetros

value
Char

O caractere Unicode a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte um Char em um String.

C#
public void ConvertStringChar(string stringVal) {
    char charVal = 'a';

    // A string must be one character long to convert to char.
    try {
        charVal = System.Convert.ToChar(stringVal);
        System.Console.WriteLine("{0} as a char is {1}",
            stringVal, charVal);
    }
    catch (System.FormatException) {
        System.Console.WriteLine(
            "The string is longer than one character.");
    }
    catch (System.ArgumentNullException) {
        System.Console.WriteLine("The string is null.");
    }

    // A char to string conversion will always succeed.
    stringVal = System.Convert.ToString(charVal);
    System.Console.WriteLine("The character as a string is {0}",
            stringVal);
}

Comentários

Essa implementação é idêntica a Char.ToString.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(DateTime)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do DateTime especificado na representação de cadeia de caracteres equivalente.

C#
public static string ToString (DateTime value);

Parâmetros

value
DateTime

O valor de data e tempo a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de um DateTime valor em um String valor.

C#
DateTime[] dates = { new DateTime(2009, 7, 14),
                     new DateTime(1, 1, 1, 18, 32, 0),
                     new DateTime(2009, 2, 12, 7, 16, 0) };
string result;

foreach (DateTime dateValue in dates)
{
   result = Convert.ToString(dateValue);
   Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        dateValue.GetType().Name, dateValue,
                        result.GetType().Name, result);
}
// The example displays the following output:
//    Converted the DateTime value 7/14/2009 12:00:00 AM to a String value 7/14/2009 12:00:00 AM.
//    Converted the DateTime value 1/1/0001 06:32:00 PM to a String value 1/1/0001 06:32:00 PM.
//    Converted the DateTime value 2/12/2009 07:16:00 AM to a String value 2/12/2009 07:16:00 AM.

Comentários

Essa implementação é idêntica a DateTime.ToString(). Ele usa as convenções de formatação da cultura atual e do especificador de formato "G" para converter um DateTime valor em sua representação de cadeia de caracteres.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Double)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do número de ponto flutuante de precisão dupla especificado em sua representação de cadeia de caracteres equivalente.

C#
public static string ToString (double value);

Parâmetros

value
Double

O número de ponto flutuante de precisão dupla a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte um Double em um String.

C#
public void ConvertDoubleString(double doubleVal) {
    
    string	stringVal;

    // A conversion from Double to string cannot overflow.
    stringVal = System.Convert.ToString(doubleVal);
    System.Console.WriteLine("{0} as a string is: {1}",
        doubleVal, stringVal);

    try {
        doubleVal = System.Convert.ToDouble(stringVal);
        System.Console.WriteLine("{0} as a double is: {1}",
            stringVal, doubleVal);
    }
    catch (System.OverflowException) {
        System.Console.WriteLine(
            "Conversion from string-to-double overflowed.");
    }
    catch (System.FormatException) {
        System.Console.WriteLine(
            "The string was not formatted as a double.");
    }
    catch (System.ArgumentException) {
        System.Console.WriteLine(
            "The string pointed to null.");
    }
}

Comentários

Essa implementação é idêntica a Double.ToString().

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Int16)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do inteiro com sinal de 16 bits especificado em sua representação de cadeia de caracteres equivalente.

C#
public static string ToString (short value);

Parâmetros

value
Int16

O inteiro assinado de 16 bits a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de inteiros de 16 bits em sua representação de cadeia de caracteres equivalente.

C#
short[] numbers = { Int16.MinValue, -138, 0, 19, Int16.MaxValue };
string result;

foreach (short number in numbers)
{
   result = Convert.ToString(number);
   Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
}
// The example displays the following output:
//    Converted the Int16 value -32768 to the String value -32768.
//    Converted the Int16 value -138 to the String value -138.
//    Converted the Int16 value 0 to the String value 0.
//    Converted the Int16 value 19 to the String value 19.
//    Converted the Int16 value 32767 to the String value 32767.

Comentários

Essa implementação é idêntica a Int16.ToString().

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Int32)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do inteiro com sinal de 32 bits especificado em sua representação de cadeia de caracteres equivalente.

C#
public static string ToString (int value);

Parâmetros

value
Int32

O inteiro com sinal de 32 bits a converter.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir compara o ToString(Int32) método com o ToString(UInt16, IFormatProvider) método . Ele define um objeto personalizado NumberFormatInfo que usa a picada "menos" para representar o sinal negativo. Ele converte cada elemento em uma matriz de inteiros em sua representação de cadeia de caracteres equivalente usando a formatação padrão (as convenções de formatação da cultura atual) e o provedor de formato personalizado.

C#
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      // Create a NumberFormatInfo object and set its NegativeSigns
      // property to use for integer formatting.
      NumberFormatInfo provider = new NumberFormatInfo();
      provider.NegativeSign = "minus ";

      int[] values = { -20, 0, 100 };

      Console.WriteLine("{0,-8} --> {1,10} {2,10}\n", "Value",
                         CultureInfo.CurrentCulture.Name,
                         "Custom");
      foreach (int value in values)
         Console.WriteLine("{0,-8} --> {1,10} {2,10}",
                           value, Convert.ToString(value),
                           Convert.ToString(value, provider));
      // The example displays output like the following:
      //       Value    -->      en-US     Custom
      //
      //       -20      -->        -20   minus 20
      //       0        -->          0          0
      //       100      -->        100        100
   }
}

Comentários

Essa implementação é idêntica a Int32.ToString(). Ele formata value usando as convenções de formatação da cultura atual.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Decimal)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do número decimal especificado na representação de cadeia de caracteres equivalente.

C#
public static string ToString (decimal value);

Parâmetros

value
Decimal

O número decimal a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte um Decimal em um String.

C#
public void ConvertStringDecimal(string stringVal) {
    decimal decimalVal = 0;
    
    try {
        decimalVal = System.Convert.ToDecimal(stringVal);
        System.Console.WriteLine(
            "The string as a decimal is {0}.", decimalVal);
    }
    catch (System.OverflowException){
        System.Console.WriteLine(
            "The conversion from string to decimal overflowed.");
    }
    catch (System.FormatException) {
        System.Console.WriteLine(
            "The string is not formatted as a decimal.");
    }
    catch (System.ArgumentNullException) {
        System.Console.WriteLine(
            "The string is null.");
    }

    // Decimal to string conversion will not overflow.
    stringVal = System.Convert.ToString(decimalVal);
    System.Console.WriteLine(
        "The decimal as a string is {0}.", stringVal);
}

Comentários

Essa implementação é idêntica a Decimal.ToString().

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Object)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do objeto especificado na representação de cadeia de caracteres equivalente.

C#
public static string ToString (object value);
C#
public static string? ToString (object? value);

Parâmetros

value
Object

Um objeto que fornece o valor a ser convertido ou null.

Retornos

A representação de cadeia de caracteres de value, ou Empty se value for null.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de objetos em sua representação de cadeia de caracteres equivalente.

C#
object[] values = { false, 12.63m, new DateTime(2009, 6, 1, 6, 32, 15), 16.09e-12,
                    'Z', 15.15322, SByte.MinValue, Int32.MaxValue };
string result;

foreach (object value in values)
{
   result = Convert.ToString(value);
   Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        value.GetType().Name, value,
                        result.GetType().Name, result);
}
// The example displays the following output:
//    Converted the Boolean value False to the String value False.
//    Converted the Decimal value 12.63 to the String value 12.63.
//    Converted the DateTime value 6/1/2009 06:32:15 AM to the String value 6/1/2009 06:32:15 AM.
//    Converted the Double value 1.609E-11 to the String value 1.609E-11.
//    Converted the Char value Z to the String value Z.
//    Converted the Double value 15.15322 to the String value 15.15322.
//    Converted the SByte value -128 to the String value -128.
//    Converted the Int32 value 2147483647 to the String value 2147483647.

Comentários

Para converter value em sua representação de cadeia de caracteres, o método tenta chamar a IConvertible.ToString implementação de value. Se value não implementar a IConvertible interface , o método tentará chamar a IFormattable.ToString implementação de value. Se o valor não implementar a IFormattable interface , o método chamará o ToString método do tipo subjacente de value.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(SByte)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Importante

Esta API não está em conformidade com CLS.

Converte o valor do inteiro com sinal de 8 bits especificado em sua representação de cadeia de caracteres equivalente.

C#
[System.CLSCompliant(false)]
public static string ToString (sbyte value);

Parâmetros

value
SByte

O inteiro com sinal de 8 bits a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Atributos

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de bytes com sinal em sua representação de cadeia de caracteres equivalente.

C#
sbyte[] numbers = { SByte.MinValue, -12, 0, 16, SByte.MaxValue };
string result;

foreach (sbyte number in numbers)
{
   result = Convert.ToString(number);
   Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
}
// The example displays the following output:
//    Converted the SByte value -128 to the String value -128.
//    Converted the SByte value -12 to the String value -12.
//    Converted the SByte value 0 to the String value 0.
//    Converted the SByte value 16 to the String value 16.
//    Converted the SByte value 127 to the String value 127.

Comentários

Essa implementação é idêntica a SByte.ToString().

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Single)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do número de ponto flutuante de precisão simples especificado em sua representação de cadeia de caracteres equivalente.

C#
public static string ToString (float value);

Parâmetros

value
Single

O número de ponto flutuante de precisão simples a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de Single valores em sua representação de cadeia de caracteres equivalente.

C#
float[] numbers = { Single.MinValue, -1011.351f, -17.45f, -3e-16f,
                    0f, 4.56e-12f, 16.0001f, 10345.1221f, Single.MaxValue };
string result;

foreach (float number in numbers)
{
   result = Convert.ToString(number);
   Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
}
// The example displays the following output:
//    Converted the Single value -3.402823E+38 to the String value -3.402823E+38.
//    Converted the Single value -1011.351 to the String value -1011.351.
//    Converted the Single value -17.45 to the String value -17.45.
//    Converted the Single value -3E-16 to the String value -3E-16.
//    Converted the Single value 0 to the String value 0.
//    Converted the Single value 4.56E-12 to the String value 4.56E-12.
//    Converted the Single value 16.0001 to the String value 16.0001.
//    Converted the Single value 10345.12 to the String value 10345.12.
//    Converted the Single value 3.402823E+38 to the String value 3.402823E+38.

Comentários

Essa implementação é idêntica a Single.ToString().

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(String)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Retorna a instância de cadeia de caracteres especificada; nenhuma conversão real é executada.

C#
public static string? ToString (string? value);
C#
public static string ToString (string value);

Parâmetros

value
String

A cadeia de caracteres a ser retornada.

Retornos

value é retornado inalterado.

Exemplos

O exemplo a seguir passa uma cadeia de caracteres para o ToString(String) método e chama o Object.ReferenceEquals método para confirmar se o método retorna a cadeia de caracteres original. O exemplo também chama o String.IsInterned método para garantir que as duas cadeias de caracteres não sejam idênticas porque a cadeia de caracteres original é internada.

C#
using System;

public class Example
{
   public static void Main()
   {
      String article = "An";
      String noun = "apple";
      String str1 = String.Format("{0} {1}", article, noun);
      String str2 = Convert.ToString(str1);

      Console.WriteLine("str1 is interned: {0}",
                        ! (String.IsInterned(str1) == null));
      Console.WriteLine("str1 and str2 are the same reference: {0}",
                        Object.ReferenceEquals(str1, str2));
   }
}
// The example displays the following output:
//       str1 is interned: False
//       str1 and str2 are the same reference: True

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

ToString(UInt16)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Importante

Esta API não está em conformidade com CLS.

Converte o valor do inteiro sem sinal de 16 bits especificado em uma representação de cadeia de caracteres equivalente.

C#
[System.CLSCompliant(false)]
public static string ToString (ushort value);

Parâmetros

value
UInt16

O inteiro não assinado de 16 bits a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Atributos

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de valores inteiros de 16 bits sem sinal em sua representação de cadeia de caracteres equivalente.

C#
ushort[] numbers = { UInt16.MinValue, 103, 1045, UInt16.MaxValue };
string result;

foreach (ushort number in numbers)
{
   result = Convert.ToString(number);
   Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
}
// The example displays the following output:
//    Converted the UInt16 value 0 to the String value 0.
//    Converted the UInt16 value 103 to the String value 103.
//    Converted the UInt16 value 1045 to the String value 1045.
//    Converted the UInt16 value 65535 to the String value 65535.

Comentários

Essa implementação é idêntica a UInt16.ToString().

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(UInt32)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Importante

Esta API não está em conformidade com CLS.

Converte o valor do inteiro sem sinal de 32 bits especificado na representação de cadeia de caracteres equivalente.

C#
[System.CLSCompliant(false)]
public static string ToString (uint value);

Parâmetros

value
UInt32

O inteiro sem sinal de 32 bits a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Atributos

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de inteiros sem sinal em sua representação de cadeia de caracteres equivalente.

C#
uint[] numbers = { UInt32.MinValue, 103, 1045, 119543, UInt32.MaxValue };
string result;

foreach (uint number in numbers)
{
   result = Convert.ToString(number);
   Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
}
// The example displays the following output:
//    Converted the UInt32 value 0 to the String value 0.
//    Converted the UInt32 value 103 to the String value 103.
//    Converted the UInt32 value 1045 to the String value 1045.
//    Converted the UInt32 value 119543 to the String value 119543.
//    Converted the UInt32 value 4294967295 to the String value 4294967295.

Comentários

Essa implementação é idêntica a UInt32.ToString().

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(UInt64)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Importante

Esta API não está em conformidade com CLS.

Converte o valor do inteiro sem sinal de 64 bits especificado na representação de cadeia de caracteres equivalente.

C#
[System.CLSCompliant(false)]
public static string ToString (ulong value);

Parâmetros

value
UInt64

O inteiro sem sinal de 64 bits a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Atributos

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de inteiros longos sem sinal em sua representação de cadeia de caracteres equivalente.

C#
ulong[] numbers = { UInt64.MinValue, 1031, 189045, UInt64.MaxValue };
string result;

foreach (ulong number in numbers)
{
   result = Convert.ToString(number);
   Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
}
// The example displays the following output:
//    Converted the UInt64 value 0 to the String value 0.
//    Converted the UInt64 value 1031 to the String value 1031.
//    Converted the UInt64 value 189045 to the String value 189045.
//    Converted the UInt64 value 18446744073709551615 to the String value 18446744073709551615.

Comentários

Essa implementação é idêntica a UInt64.ToString().

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToString(Int64)

Origem:
Convert.cs
Origem:
Convert.cs
Origem:
Convert.cs

Converte o valor do inteiro com sinal de 64 bits especificado em sua representação de cadeia de caracteres equivalente.

C#
public static string ToString (long value);

Parâmetros

value
Int64

O inteiro com sinal de 64 bits a ser convertido.

Retornos

A representação da cadeia de caracteres de value.

Exemplos

O exemplo a seguir converte cada elemento em uma matriz de inteiros longa em sua representação de cadeia de caracteres equivalente.

C#
// Create a NumberFormatInfo object and set several of its
// properties that control default integer formatting.
System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();
provider.NegativeSign = "minus ";

long[] values = { -200, 0, 1000 };

foreach (long value in values)
   Console.WriteLine("{0,-6}  -->  {1,10}",
                     value, Convert.ToString(value, provider));
// The example displays the following output:
//       -200    -->   minus 200
//       0       -->           0
//       1000    -->        1000

Comentários

Essa implementação é idêntica a Int64.ToString().

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0