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).
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
TtoUwhere 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.
Most helpful comment
Is
new InvalidCastException(typeof(int), typeof(string))actually better thannew InvalidCastException($"Cannot cast from {typeof(int)} to {typeof(string)}.")? Especially considering that throwingInvalidCastExceptionfrom user code is not very common.In some cases, when the language doesn't allow
(U)t, using an intermediary cast toobjecthelps:(U)(object)t. Have you tried that?