C#

ConvertChangeType fails on Nullable Types

25 September 2026 · 5 min read

ConvertChangeType fails on Nullable Types

Working with nullable types in C can be tricky, especially when using the Convert.ChangeType() method. Many developers encounter unexpected exceptions when attempting to convert values to nullable types. This frustrating issue often stems from a misunderstanding of how Convert.ChangeType() handles nulls and the underlying type system. This post dives into the reasons behind these failures, explores effective workarounds, and provides best practices for handling type conversions involving nullable types in your C projects.

Why Convert.ChangeType() Fails with Nullable Types

The core problem lies in the fact that Convert.ChangeType() doesn’t inherently understand nullable types. It attempts to convert the provided value to the underlying type of the nullable type, without considering the possibility of null. If the value is null or cannot be converted to the underlying type, an exception is thrown. For example, trying to convert a DBNull value or an empty string to a nullable int (int?) using Convert.ChangeType() will result in an InvalidCastException.

This behavior is documented, but often overlooked. The Convert.ChangeType() method expects a non-null value that can be directly converted to the target type. Nullable types introduce the added complexity of potentially holding a null value, which this method isn’t designed to handle directly. This discrepancy is the root cause of the common conversion failures.

Understanding this limitation is crucial for implementing robust type conversion logic. Relying solely on Convert.ChangeType() without accounting for nullability can lead to unexpected runtime errors and application instability.

Workarounds for Nullable Type Conversion

Fortunately, there are several effective workarounds to address this limitation. One common approach involves checking for null before attempting the conversion:

  1. Check if the value is null or DBNull.
  2. If it’s null, assign null to the nullable variable.
  3. If it’s not null, use Convert.ChangeType() to convert to the underlying type and assign the result to the nullable variable.

This approach ensures that null values are handled gracefully, preventing exceptions. Here’s a C example demonstrating this workaround:

object value = DBNull.Value; int? nullableInt = null; if (value != null && value != DBNull.Value) { nullableInt = (int)Convert.ChangeType(value, typeof(int)); } 

Another strategy involves using the TryParse methods provided by various types (e.g., int.TryParse, DateTime.TryParse). These methods return a boolean indicating success or failure, along with the converted value as an output parameter, allowing for cleaner and more robust error handling.

Best Practices for Type Conversion with Nullables

When dealing with nullable types and conversions, consider the following best practices:

  • Always check for null before using Convert.ChangeType().
  • Prefer TryParse methods when available for more robust error handling.
  • Consider using custom conversion logic for complex scenarios.

Implementing these practices can greatly enhance the reliability and maintainability of your code. By explicitly handling nulls and utilizing type-specific parsing methods, you can create more robust applications that are less prone to unexpected runtime errors. Proactive null checks and appropriate error handling are fundamental to writing high-quality, maintainable C code.

Leveraging Generics for Type Safety

Generic methods offer a powerful way to create reusable conversion logic. By using generics, you can create a method that handles nullable type conversions safely and efficiently without repetitive code. This approach enhances type safety and reduces the risk of errors. Consider this example:

public static T? ConvertToNullable<T>(object value) where T : struct { if (value == null || value == DBNull.Value) { return null; } return (T)Convert.ChangeType(value, typeof(T)); } 

This generic method can be used to convert values to various nullable types, improving code clarity and maintainability. It provides a centralized solution, reducing redundancy and improving consistency in how type conversions are handled throughout your codebase. This approach is especially beneficial in projects with frequent type conversions.

[Infographic about handling nullable type conversions]

FAQ: Common Questions about Convert.ChangeType() and Nullables

Q: Why does using Convert.ChangeType() with database nulls (DBNull) cause problems?

A: Convert.ChangeType() tries to convert the DBNull value directly to the underlying type of the nullable type, which isn’t possible. This leads to an InvalidCastException.

Q: Are there alternatives to Convert.ChangeType() for nullable conversions?

A: Yes, type-specific TryParse methods (like int.TryParse()) offer a more robust solution, as they handle nulls and invalid formats gracefully. Manual checks and custom conversion routines can also be implemented for more complex situations.

Handling nullable type conversions effectively is critical for writing robust and reliable C applications. While Convert.ChangeType() provides a general-purpose conversion mechanism, it falls short when dealing with the nuances of nullable types. By understanding its limitations and utilizing the workarounds and best practices discussed here—such as null checks, TryParse methods, and generic solutions—you can write cleaner, more resilient code. Remember that proactive null checks and appropriate error handling are essential components of high-quality C development. Check out Microsoft’s documentation for further insights, and explore the Stack Overflow community’s discussions on nullable type conversions for practical tips and real-world examples. You might also find this article on nullable type conversion strategies helpful. For deeper insights into generic programming in C, consider this resource: Generics in C. By incorporating these strategies, you can ensure that your code gracefully handles nulls and avoids unexpected exceptions, contributing to more stable and maintainable software.

Question & Answer :
I want to convert a string to an object property value, whose name I have as a string. I am trying to do this like so:

string modelProperty = "Some Property Name"; string value = "SomeValue"; var property = entity.GetType().GetProperty(modelProperty); if (property != null) { property.SetValue(entity, Convert.ChangeType(value, property.PropertyType), null); } 

The problem is this is failing and throwing an Invalid Cast Exception when the property type is a nullable type. This is not the case of the values being unable to be Converted - they will work if I do this manually (e.g. DateTime? d = Convert.ToDateTime(value);) I’ve seen some similiar questions but still can’t get it to work.

Untested, but maybe something like this will work:

string modelProperty = "Some Property Name"; string value = "Some Value"; var property = entity.GetType().GetProperty(modelProperty); if (property != null) { Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; object safeValue = (value == null) ? null : Convert.ChangeType(value, t); property.SetValue(entity, safeValue, null); }