.NET: How to determine if a variable can be converted to a particular type
Platform: .NET Framework
Language: C#
Using reflection, we can determine if a particular variable can be converted to another data type. This is useful if you're not sure if the conversion that you're about to perform is valid or not. Although this can be done using the common way of converting, for example:
int x = 10;
Convert.ToDateTime(x);
However, the previous code will throw an exception, so you're obligated to enclose the code in the "try...catch" block. Exceptions are, however, expensive operations and can be avoided in cases of invalid conversions. By changing the above code to:
using System.ComponentModel;
...
...
...
int x = 10;
IConvertible c = x as IConvertible;
if (c == null)
{
// code here
}
if (TypeDescriptor.GetConverter(x).CanConvertTo(typeof(System.DateTime)) == false)
{
// code for invalid conversion here
}
you can avoid using exceptions just to handle invalid conversions.
I know what you're thinking, it takes several lines more than the "common" way.... but you can encapsulate all this code into a conversion function, and using the above code would become more "convenient". One thing to note though, the "CanConvertTo" returns false when checking if a string variable can be converted to a boolean type. So special handling should be done within the function for such a case.
I've attached a simple console app demonstrating this. Also, take note of the "IConvertible.ToType" conversion function in the attachment. Very useful, IMHO.
For further information, refer to the MSDN documentation on the TypeDescriptor, TypeConverter classes and the IConvertible interface.
HYFTU