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.
For implicit types (int
, float
, etc) you can use a TypeConverter
to determine if a variable of type a can be converted to type b. You can find a reference to the appropriate type converter by using one of the overloads of TypeDescriptor.GetConverter
(System.ComponentModel).
For custom or other reference types, I would recommend Type.IsAssignableFrom
(as referenced in the question). The proper use of such method would be:
var implType = typeof(List<>);
if (typeof(IEnumerable).IsAssignableFrom(implType))
Console.WriteLine("'{0}' is convertible to '{1}'", implType, typeof(IEnumerable));
The above example will tell you whether the type List<T>
is convertible to IEnumerable
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With