Static boolean method that can check whether a value can be converted to a specified type

Type conversion are at times error prone than any of our code statements, The following method checks data types for this. It supports all the CLR Primitive types such as guid, double, int, and enums like color etc.

e.g. CanConvert("egghead", typeof(int)); //returns false;
CanConvert("orange", typeof(System.Drawing.Color)); //returns true;

/// <summary>
/// Determines whether the specified value can be converted to the specific type
/// </summary>
/// <param name="value">The value in question.</param>
/// <param name="type">The result type.</param>
/// <returns>
///     <c>true</c> if specified value can be converted to the specific type; otherwise, <c>false</c>.
/// </returns>

public static bool CanConvert(string value, Type type)
{
     if (type == null || string.IsNullOrEmpty(value))
       return false;

     System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(type);
            if (conv.CanConvertFrom(typeof(string)))
            {
                try
                {
                    conv.ConvertFrom(value);
                    return true;
                }
                catch
                { 
                    //escape the catch
                }
            }

            return false;
        }
By [)ia6l0 iii   Popularity  (2027 Views)