Back to Blog
C#

C# Convert Usage: Converting Between Base Types

c# convert usage: How to use the C# Convert class for type conversion, including null and DBNull handling and choosing between Convert, Parse, TryParse, and casting.

C#.NETtype conversionConvert classparsingTryParse
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. When you look up c# convert usage, 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 operates on the .NET base types: Boolean, Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, Char, String, DateTime, and DBNull. Each conversion method accepts an object and returns the target type.

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. Because the input parameter is typed as object, the same method 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
Convert.ToString(null)string.EmptyNo failure; calls ToString() on the value
Convert.ToBoolean(null)falseFormatException for unrecognized text
Convert.ToDateTime(null)DateTime.MinValueFormatException for unrecognized text

This null-handling behavior makes Convert convenient when the input comes from an external source that may be empty or absent. 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, only works when the runtime type of value is already an int or a type with an explicit conversion to int. It never parses text. If value is a boxed long, a cast to int throws InvalidCastException even though 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, char, and DateTime inputs. The cost of that flexibility is that the input is typed as object, so the compiler cannot verify that the conversion is valid at compile time.

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.

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.

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

Because Convert methods accept object, each call may involve boxing and a runtime type check. For a one-off conversion in application code, that cost is irrelevant. In a tight loop that converts millions of values, int.Parse on a known string or a direct cast on a known type avoids that overhead. The mechanism, not a benchmark, is the reason: Parse operates directly on string, while Convert must inspect the runtime type of its object argument.

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.

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 the value already has the target type and you are narrowing it, such as converting a long to an int after checking the range. 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.

c# convert usage: Practical Usage and Code Examples | RYUSLOG DEV