Converting integer to string in C#

Asked

Viewed 3,455 times

0

How do I convert an integer to a string? I have tried to search in places and did not find the answer, I have this problem just to finalize my project, if someone can collaborate, I would appreciate!

  • Bear in mind the kind of questions you raise, questions that are too general risk being closed. I recommend reading the forum guidelines at https://answall.com/help

3 answers

7

Use the extension method ToString():

int numero = 10;
string numeroString = numero.ToString();

An observation, if your entire variable accepts null values and is null, when using the method ToString() error will occur NullReferenceException. To avoid this problem use the method Convert.ToString(), if the value is null it will return empty string.

int? numero = null;

// O retorno será ""
string numeroString = Convert.ToString(numero);

// Será lançada a exceção NullReferenceException
string numeroStringComErro = numero.ToString();

2

Just use the Convert.Tostring;

var x = 2;

var result = Convert.ToString(x);

1

Hello

There are several ways to treat the conversion and types in the . NET, the implicit and explicit, in this case the explicit is the recommended.

int numero = 10:
string explicitString1 = numero.ToString();
// ou
string explicitString2 = Convert.ToString(numero);

By the way the implicit will be something like this

int valor1 = 10;

object valor2 = valor1;

// converter implicitamente 
int valor3 = (int)valor2;
  • You call the two examples "explicit"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.