Check if type TA can use type TB at runtime? (Given something more than inheritance)

So, I know this works:

class A { } class B : A { } [Test] public void CanCast() { Assert.That(typeof(A).IsAssignableFrom(typeof(B))); Assert.That(!typeof(B).IsAssignableFrom(typeof(A))); } 

However, let's say that the two types were Int32 and Int64.

At runtime, I can assign an Int32 value to an Int64 variable, but not vice versa. How can I check this compatibility at runtime? (IsAssignableFrom does not work for this, it always gives false for Int32 and Int64)

EDIT: I can’t just try to make a throw because I don’t have a value for these types, I am specifying a hypothetical scenario for having two types A and B without two values ​​a and b.

+4
source share
2 answers

For non-primitive types, you can map and check if the op_Implicit method op_Implicit for any type that supports conversion. IL does not actually support true operator overloading, so this is a pure C # notation for recognizing operator overloads. This method will also be marked as IsSpecialName if it was created from an operator overload definition in C #.

For primitive types (for example, Int32 and Int64), the simplest option is hard coding of various cases, since the conversion is performed using the primitive IL operation code and not through the method. However, there are only a few primitive types, so it’s easy to create a method that checks all the possibilities for each primitive type.

One-way note, since your example mentions specific types of values, note that the existence of an implicit “conversion” (in C #) does not mean that all “throws” will work. The C # cast (T)x operation may also mean "unbox value from x to enter T". If x contains a nested Int32 package and you try (Int64) x, this will fail at run time, although you can implicitly "convert" Int32 to Int64. See Eric Lippert for more information on why unpacking works this way.

+6
source

One (less elegant) approach is to just try - wrap the try in try / catch and Assert false if you catch an exception.

-1
source

Source: https://habr.com/ru/post/1438028/


All Articles