Convert.ToString() / Convert.ToInt32()
Methods of the .NET type conversion utility class Convert, such as Convert.ToString() for converting values to strings and Convert.ToInt32() for converting values to integers.
Syntax
// Converts a value to a string. Convert.ToString(object value) // Converts a value to a 32-bit integer (int). Convert.ToInt32(object value) // Converts a value to a double-precision floating-point number (double). Convert.ToDouble(object value) // Converts a value to a boolean (bool). Convert.ToBoolean(object value)
Method List
| Method | Description |
|---|---|
| Convert.ToString(object value) | Converts a value to a string. Returns an empty string "" if null is passed. |
| Convert.ToInt32(object value) | Converts a value to an int. Returns 0 if null is passed. |
| Convert.ToDouble(object value) | Converts a value to a double. |
| Convert.ToBoolean(object value) | Converts a value to a bool. 0 becomes false; any other value becomes true. |
| Convert.ToInt32(string value, int fromBase) | Converts a string in the specified base (2, 8, 16, etc.) to an int. |
Sample Code
using System;
// Convert a number to a string using Convert.ToString().
int age = 25;
string ageStr = Convert.ToString(age);
Console.WriteLine("Age: " + ageStr); // Age: 25
// Convert a string to an integer using Convert.ToInt32().
string input = "100";
int value = Convert.ToInt32(input);
Console.WriteLine(value * 2); // 200
// Convert a string to a floating-point number using Convert.ToDouble().
double temperature = Convert.ToDouble("36.5");
Console.WriteLine(temperature); // 36.5
// Example of Convert.ToBoolean().
Console.WriteLine(Convert.ToBoolean(1)); // True
Console.WriteLine(Convert.ToBoolean(0)); // False
// Convert a hexadecimal string to an integer.
int colorCode = Convert.ToInt32("FF", 16);
Console.WriteLine(colorCode); // 255
// Difference from .ToString(): Convert.ToString(null) returns "".
string? nullValue = null;
Console.WriteLine(Convert.ToString(nullValue) == ""); // True
Notes
The key difference between Convert class methods and int.Parse() is how they handle null. Convert.ToInt32(null) returns 0, whereas int.Parse(null) throws an exception.
When conversion may fail — such as with user input — consider using int.TryParse(), which does not throw an exception. For checking null or empty strings, string.IsNullOrEmpty() is a convenient option.
If you find any errors or copyright issues, please contact us.