OneBite.Dev - Coding blog in a bite size

Convert Variable From Int To String In C#

Code snippet for how to Convert Variable From Int To String In C# with sample and detail explanation

Converting variables from one data type to another is a common operation in programming. In this article, we will specifically discuss how to convert an int variable to a string in C#.

Code snippet for int to string conversion

Here is a simple piece of code that shows how to convert an int to a string in C#:

int number = 12345;
string result = number.ToString();
Console.WriteLine(result);

Code Explanation for int to string conversion

In the provided code snippet, we essentially leveraged C#‘s built-in method for converting int to string, so let’s break it down step by step:

  1. Defining an integer: First, we created an int variable named number and assigned the value 12345 to it. This is the integer we want to convert to a string.

    int number = 12345;
  2. Conversion: To convert the integer to a string, we used the ToString method. This method is part of the System.Int32structure which represents a 32-bit signed integer.

    string result = number.ToString();

    The ToString function, when called on an integer value, converts the integer value to a textual representation and returns it. Here we store that textual representation in the string variable result.

  3. Printing the result: The last line of code prints out the result of the conversion.

    Console.WriteLine(result);

Now, when you run this simple C# program, it would print 12345, verifying that the conversion has been successful. Feel free to adjust the number value in the code snippet to further experiment with the process.

c-sharp