Know if variable of type A can be casted to type B
I know that I can cast (implicitly) a int to a float, or a float to a double.
Also, I can cast (explicitly) a double to a float, or to an int.
This can be proved by the following example:
int i;
float f;
// The smaller type fits into the bigger one
f = i;
// And the bigger type can be cut (losing precision) into a smaller
i = (int)f;
The problem is that this types aren't inherited one from another (int
isn't a subtype of float or vice-versa).
They have implemented a implicit/explicit casting operator or something
like that. If not, it works like it is...
My question is: How can I check if a variable of type A can be casted to
type B.
I've tried i.GetType().IsAssignableFrom(f.GetType()), but
Type.IsAssignableFrom(Type) only checks inheritance and interfaces (and
maybe something more), but doesn't check the implemented casting operator.
I've tried i is float and f is int, but the effect is the same.
No comments:
Post a Comment