Runtime: InvalidCastException(Type, Type) with appropriate message

Created on 25 Nov 2017  路  2Comments  路  Source: dotnet/runtime

for lazy developers like me, id like to have InvalidCastException(Type, Type) that gives exact runtime error message when trying to cast from T to U.

so when I throw

 throw new InvalidCastException(typeof(int), typeof(string));

I should get this message (something like this).

can not cast from System.Int32 to System.String

currently I have to do the formatting and writing all message by myself

Why am I trying to throw invalid cast exception?

because appreantly I cant explicitly cast from generic type T to U where both are constrained to one class. so I'm forced to do safe cast, and in case its null, throw appropriate exception (by contract T is never null so if safe cast results in null that's definitely cast failure).

Most helpful comment

Is new InvalidCastException(typeof(int), typeof(string)) actually better than new InvalidCastException($"Cannot cast from {typeof(int)} to {typeof(string)}.")? Especially considering that throwing InvalidCastException from user code is not very common.


I cant explicitly cast from generic type T to U where both are constrained to one class

In some cases, when the language doesn't allow (U)t, using an intermediary cast to object helps: (U)(object)t. Have you tried that?

All 2 comments

Is new InvalidCastException(typeof(int), typeof(string)) actually better than new InvalidCastException($"Cannot cast from {typeof(int)} to {typeof(string)}.")? Especially considering that throwing InvalidCastException from user code is not very common.


I cant explicitly cast from generic type T to U where both are constrained to one class

In some cases, when the language doesn't allow (U)t, using an intermediary cast to object helps: (U)(object)t. Have you tried that?

In some cases, when the language doesn't allow (U)t, using an intermediary cast to object helps: (U)(object)t. Have you tried that?

oh great! it works like a charm.

yes, its not very common to throw this exception manually (never happened to me before). but I thought its not a big deal either.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

btecu picture btecu  路  3Comments

EgorBo picture EgorBo  路  3Comments

bencz picture bencz  路  3Comments

jzabroski picture jzabroski  路  3Comments

jamesqo picture jamesqo  路  3Comments