Alex Rivera | Logout

Test if Convert.ChangeType will work between two types

Asked 2009-09-09T12:04:18.757
34

This is a follow-up to this question about converting values with reflection. Converting an object of a certain type to another type can be done like this:

object convertedValue = Convert.ChangeType(value, targetType);

Given two Type instances (say FromType and ToType), is there a way to test whether the conversion will succeed?

E.g. can I write an extension method like this:

public static class TypeExtensions
{
    public static bool CanChangeType(this Type fromType, Type toType)
    {
        // what to put here?
    }
}

EDIT: This is what I have right now. Ugly, but I don't see another way yet...

bool CanChangeType(Type sourceType, Type targetType)
{
  try
  {
    var instanceOfSourceType = Activator.CreateInstance(sourceType);
    Convert.ChangeType(instanceOfSourceType, targetType);
    return true; // OK, it can be converted
  }
  catch (Exception ex)
  {
    return false;
  }
Edit
Report

2 Answers

33

I was just encountering this same issue, and I used Reflector to look at the source for ChangeType. ChangeType throws exceptions in 3 cases:

  1. conversionType is null
  2. value is null
  3. value does not implement IConvertible

After those 3 are checked, it is guaranteed that it can be converted. So you can save a lot of performance and remove the try{}/catch{} block by simply checking those 3 things yourself:

public static bool CanChangeType(object value, Type conversionType)
{
    if (conversionType == null)
    {
        return false;
    }

    if (value == null)
    {              
        return false;
    }

    IConvertible convertible = value as IConvertible;

    if (convertible == null)
    {
        return false;
    }

    return true;
}
answered 2010-11-04T22:32:12.607
0

I have written a little framework that includes a Convert class that can do more than the System.Convert class. If you are interested in using it, you can download it from Github. It doesn't have the ability to determine if you can convert between values, but that seems like a good feature to add.

It does include the ability to convert values based on:

  • IConvertible
  • TypeConverters
  • ToXxx methods
  • Parse static methods
  • Parameterized constructor
  • and a few other minor ones

Data Type Conversions

answered 2009-09-09T18:49:44.263

Your Answer