Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Know if variable of type A can be casted to type B

Tags:

c#

casting

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.

like image 280
NemoStein Avatar asked Nov 11 '22 23:11

NemoStein


1 Answers

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.

like image 178
M.Babcock Avatar answered Nov 14 '22 22:11

M.Babcock