Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Convert Usage: Converting Between Base Types

How to use the C# Convert class for type conversion, including null and DBNull handling, culture behavior, and when to choose Convert, Parse, TryParse, or casting.

~6 min readC#
#C##.NET#type conversion#Convert class
Illustration of the C# Convert class transforming a value into different data types such as string, integer, and boolean.

What the Convert Class Does

The Convert class in .NET is a static utility that converts a value from one base type to another. The practical question is usually whether Convert is the right tool for a particular conversion and how it differs from casting, parsing, or calling ToString() directly.

Convert has methods for the .NET base types: Boolean, Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, Char, String, and DateTime. Most methods have typed overloads and an object overload. Convert also recognizes DBNull.Value as a special input for database work, but DBNull is not a base type.

csharp
int number = Convert.ToInt32("42"); string text = Convert.ToString(123); bool flag = Convert.ToBoolean(1);

The first line parses the string "42" into the integer 42. The second converts an integer to its string representation. The third converts 1 to true. When you use the object overload, the same method name can accept a string, a number, or any other runtime type.

Common Convert Methods and Their Behavior

The methods you will reach for most often are ToInt32, ToString, ToBoolean, ToDouble, ToDecimal, and ToDateTime. Each has overloads for the different base types, and each has specific behavior for null input.

Convert.ToString is notable because it returns string.Empty when the input is null, whereas calling ToString() directly on a null reference throws NullReferenceException. Convert.ToInt32 returns 0 for null input, Convert.ToBoolean returns false, and Convert.ToDateTime returns DateTime.MinValue.

MethodNull input resultInvalid input result
Convert.ToInt32(null)0FormatException for non-numeric text, OverflowException when the value exceeds the Int32 range
Convert.ToString(null)string.EmptyNo parse failure; returns the value's string representation
Convert.ToBoolean(null)falseFormatException for unrecognized text
Convert.ToDateTime(null)DateTime.MinValueFormatException for unrecognized text

This null-handling behavior makes Convert convenient when an external value can be null. It also means you cannot distinguish "the value was null" from "the value was zero" without checking the source yourself.

Convert vs. Parse vs. TryParse vs. Casting

The most common source of confusion is choosing between Convert, Parse, TryParse, and a direct cast. They solve different problems.

A cast, such as (int)value, never parses text. For a non-object type, it succeeds when an explicit conversion exists, such as from long to int. For an object variable, the cast is an unboxing conversion and succeeds only when the runtime type is exactly int; a boxed long throws InvalidCastException even when the numeric value fits.

int.Parse(string) parses a string and throws FormatException when the text is invalid and ArgumentNullException when the input is null. int.TryParse(string, out int result) does the same parsing but returns false instead of throwing, which makes it the natural choice for user input that is expected to fail sometimes.

Convert.ToInt32(string) parses text like Parse, but it also accepts null (returning 0) and accepts other numeric types, bool, and char. The DateTime overload exists, but converting a date and time to an integer throws InvalidCastException, so it is not a meaningful numeric conversion. The cost of the flexibility is that when you use the object overload, the compiler cannot verify that the conversion is valid at compile time.

csharp
string input = "42"; int viaConvert = Convert.ToInt32(input); int viaParse = int.Parse(input); bool parsed = int.TryParse(input, out int viaTryParse);

All three produce the same value for valid input. The difference appears in failure handling: Convert returns a default for null, Parse throws, and TryParse signals failure through its return value.

Handling null and DBNull Values

When reading values from a database, a column can contain DBNull.Value rather than null. This is a common source of InvalidCastException with Convert.

Convert.ToInt32(DBNull.Value) throws because DBNull is not null; it is a distinct type that represents an absent database value. The null-handling behavior of Convert does not apply to DBNull.

csharp
object raw = reader["Age"]; int? age = raw == DBNull.Value ? null : Convert.ToInt32(raw);

This pattern checks for DBNull explicitly before converting. It is the standard approach when mapping database rows to domain objects. For numeric conversions such as ToInt32, DBNull throws InvalidCastException. Convert.ToString does not throw because DBNull.ToString() returns string.Empty, but the result is indistinguishable from an empty string, which may or may not be what you want.

Culture and Formatting in Conversions

The string overloads of Convert use the current culture by default. This matters for decimal separators, date formats, and number grouping.

csharp
double value = Convert.ToDouble("3.14", CultureInfo.InvariantCulture);

In a culture that uses a comma as the decimal separator, Convert.ToDouble("3.14") without a format provider would throw FormatException. Passing CultureInfo.InvariantCulture makes the conversion predictable regardless of the machine's regional settings.

The same applies to output. Convert.ToString(decimalValue) formats the number using the current culture, so the same value can produce different strings on different machines. When the result is stored in a file, sent over a wire, or used in a log that must be parsed later, pass CultureInfo.InvariantCulture explicitly.

Exception Behavior and Error Handling

Convert combines several behaviors in one call: null becomes a default value, valid text is parsed, and invalid text throws. Understanding which exception each failure produces helps you handle them correctly.

Convert.ToInt32("abc") throws FormatException. Convert.ToInt32("2147483648") throws OverflowException because the value exceeds the Int32 range. Convert.ToInt32(DBNull.Value) throws InvalidCastException.

When the input is user-provided text, catching FormatException is usually the wrong design. int.TryParse communicates the possibility of failure through its return value and avoids exception overhead in the failure path. Convert is better suited to inputs you expect to be valid, such as values already produced by your own code or by a well-defined data source.

Performance and Maintainability Considerations

When you call the object overload of a Convert method, the argument may be boxed and the method must inspect the runtime type. For a one-off conversion in application code, that cost is irrelevant. In a tight loop that converts millions of values, use the overload that matches the static type: int.Parse on a known string, a direct cast on a known numeric type, or the typed Convert overload for that type. The mechanism, not a benchmark, is the reason: for a string input, the typed Convert overload and int.Parse both avoid the extra object dispatch; the object overload is the one to avoid in a hot path.

Maintainability is the more significant concern. Convert.ToInt32(someObject) hides what the input actually is. If the input is always a string, int.TryParse documents that intent and makes the failure mode explicit. If the input is a database value that may be DBNull, the explicit DBNull check is clearer than relying on Convert's null behavior. Prefer the API that matches the actual input type.

When to Use Convert vs. Alternatives

Use Convert when the input is an object whose runtime type you do not control, such as a value from reflection, a database reader, or a generic API, and when a null input should become the type's default value. If the source can be DBNull.Value, add the explicit DBNull check described above.

Use int.Parse when the input is a string that must be valid, and an exception is the correct signal for invalid data.

Use int.TryParse when the input is user-provided or otherwise expected to fail, and you want to branch on the result without exceptions.

Use a direct cast when you have a typed value with a defined explicit conversion, such as narrowing a long to an int after checking the range. For a value stored as object, a cast is safe only when the runtime type is exactly the target type. A cast is also the only option that preserves reference identity for reference types.

The decision is not about which API is more powerful. It is about which API matches the certainty you have about the input. Convert trades compile-time safety for runtime flexibility; Parse and TryParse trade flexibility for explicit string handling. Choose the one that reflects what your code actually knows.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.