In C#, System.Convert is the standard way to change a value from one type to another: read numbers with ToInt32(), build text with ToString(), flip bools with ToBoolean(), and encode bytes as Base64 or hex.
Most beginner programs start with using System; and then call Convert.ToInt32("42") or Convert.ToString(99).
This page introduces Convert. The Convert Methods index lists every method guide in this series.
Null and exceptions.
For many numeric To* overloads, a null argument becomes 0. Invalid text still throws FormatException, and values that do not fit throw OverflowException.
Syntax
C# Syntax
Common first calls:
C#
int n = Convert.ToInt32("42");
string s = Convert.ToString(3.14);
bool b = Convert.ToBoolean("True");
Console.WriteLine(Convert.ToInt32("42"));
Reference
Convert vs Parse
A quick map of how Convert compares to type Parse helpers:
API
Null input
Bad text
Convert.ToInt32
Often returns 0
FormatException
int.Parse
Throws
FormatException
int.TryParse
Returns false
Returns false (no throw)
Code
C# Examples
Three short programs that show everyday Convert calls.
Example 1 — Parse a Number with ToInt32
A first program that converts a digit string into an int.
C#
using System;
class Program {
static void Main() {
int n = Convert.ToInt32("42");
Console.WriteLine(n);
Console.WriteLine(n + 8);
}
}
Output
42
50
How It Works
String in."42" is text until Convert turns it into a number.
ToInt32. The call returns a 32-bit signed integer.
Use as int. Adding 8 works because n is numeric, not text.
Example 2 — Turn Values into Text with ToString
Show how Convert.ToString builds display text from numbers and bools.
C#
using System;
class Program {
static void Main() {
Console.WriteLine(Convert.ToString(99));
Console.WriteLine(Convert.ToString(true));
Console.WriteLine(Convert.ToString(3.5));
}
}
Output
99
True
3.5
How It Works
Any common type. Numbers and bools become culture-aware text.
Bool spelling.true prints as True.
Ready to print. The results are strings you can concatenate or log.
Example 3 — See Convert Null Behavior
Compare Convert.ToInt32(null) with a normal digit string.
C#
using System;
class Program {
static void Main() {
Console.WriteLine(Convert.ToInt32("10"));
Console.WriteLine(Convert.ToInt32(null));
}
}
Output
10
0
How It Works
Valid digits."10" converts to integer 10.
Null becomes zero. For many numeric To* overloads, null yields 0.
Unlike Parse.int.Parse(null) throws—Convert is more forgiving on null.
Continue
Next: C# Convert Methods Index
After you know what Convert is for, open the method index for a full tutorial on each System.Convert API.