How to (really) check if type A is assignable from type B

R

Rickard

I want to dynamically check if I can assign from type A to type B in
runtime. Type.IsAssignableFrom does not work for me as,

typeof(int).IsAssignableFrom(typeof(short))

returns false, which is incorrect in the (english) meaning of "Is
assignable from".

Is there a function that checks if the assignment will throw an
InvalidCastException?
Simply using
try {
} catch (InvalidCastException) {}
does not work either because I don't want to do the actual assignment,
but do different processing depending on if the types CAN be assigned.

Thanks in advance for any help/suggestions.

/ Rickard
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

No idea what you are trying to do. but if you can assure that you only have
reference types you can use the "as" operator.
 
R

Rickard

Ignacio said:
Hi,

No idea what you are trying to do. but if you can assure that you only have
reference types you can use the "as" operator.

Hello,
Thanks for the reply.

What I want is a function,

bool CheckIfAssignmentIsPossible(object o, Type t)
{
}

that returns "true" if the following assignment will later on fail

MyType myVar = (MyType)o;

where MyType is the type whose reflection type is the "t" parameter to
the above function.

Note here that I don't have the type at runtime, I need to use reflection.

My code does not have control over the assigment, it is in a different
assembly.

Right now I have a special case function for integers, and uses
IsAssigableFrom for all the others. I'm not sure this is correct, but
I've encountered no problems yet.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top