Type Data From InvalidCastException

.net, c#, types

Solution

One solution could be to implement a Cast function which gives you that information if the cast doesn't succeed:

static void Main(string[] args)
{
    try
    {
        string a = Cast<string>(1);
    }
    catch (InvalidCastExceptionEx ex)
    {
        Console.WriteLine("Failed to convert from {0} to {1}.", ex.FromType, ex.ToType);
    }
}



public class InvalidCastExceptionEx : InvalidCastException
{
    public Type FromType { get; private set; }
    public Type ToType { get; private set; }

    public InvalidCastExceptionEx(Type fromType, Type toType)
    {
        FromType = fromType;
        ToType = toType;
    }
}

static ToType Cast<ToType>(object value)
{
    try
    {
        return (ToType)value;
    }
    catch (InvalidCastException)
    {
        throw new InvalidCastExceptionEx(value.GetType(), typeof(ToType));
    }
}

Problem

The question is pretty simple: is there any way to get the problematic `System.Type`s from an `InvalidCastException`? I want to be able to display information about the failed type casting in a format such as "Expected {to-type}; found {from-type}", but I cannot find a way to access the types that were involved. EDIT: The reason I need to be able to access the types that were involved is because I have information about shorter names for some times. For example, instead of the type `RFSmallInt`, I want to say that the type is actually `smallint`. Instead of an error message ``` Unable to cast object of type 'ReFactor.RFSmallInt' to type 'ReFactor.RFBigInt'. ``` I actually want to display ``` Expected bigint; recieved smallint. ```

Original source