The question is pretty simple: is there any way to get the problematic System.Types 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.
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));
}
}
I've done this kind of thing with a custom exception:
public class TypeNotImplementedException : Exception {
public Type ToType { get { return _ToType; } }
private readonly Type _ToType;
public Type FromType { get { return _FromType; } }
private readonly Type _FromType;
public override System.Collections.IDictionary Data {
get {
var data = base.Data ?? new Hashtable();
data["ToType"] = ToType;
data["FromType"] = FromType;
return data;
}
}
public TypeNotImplementedException(Type toType, Type fromType, Exception innerException)
: base("Put whatever message you want here.", innerException) {
_ToType = toType;
_FromType = fromType;
}
}
class Program {
private static T Cast<T>(object obj) {
try {
return (T)obj;
}
catch (InvalidCastException ex) {
throw new TypeNotImplementedException(typeof(T), obj.GetType(), ex);
}
}
static void Main(string[] args) {
try {
Cast<string>("hello world" as object);
Cast<string>(new object());
}
catch (TypeNotImplementedException ex) {
Console.WriteLine(ex);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With