Example #1
0
        /// <summary>
        ///   Gets an instance of T from string.
        /// </summary>
        /// <typeparam name = "T">
        /// </typeparam>
        /// <param name = "value">The value to convert.</param>
        /// <returns>
        ///   <paramref name = "value" /> as an instance of <c>T</c> or an exception if
        ///   the conversion is not possible.
        /// </returns>
        internal static T GetTFromString <T>(string value)
        {
            Type typeOfT = typeof(T);

            try
            {
                if (IsBool <T>())
                {
                    // Need to use aliasing to get around this.
                    return(ConvertToBool <T>(value));
                }

                if (IsStringArray <T>())
                {
                    var stringArrayConverter = new StringArrayConverter();
                    return((T)stringArrayConverter.ConvertFrom(value));
                }

                if (IsByteArray <T>())
                {
                    var byteArrayConverter = new ByteArrayConverter();
                    return((T)byteArrayConverter.ConvertFrom(value));
                }

                TypeConverter converter = TypeDescriptor.GetConverter(typeOfT);
                if (converter.CanConvertFrom(StringType))
                {
                    return((T)converter.ConvertFrom(value));
                }

                throw new InvalidOperationException(string.Format(Strings.Culture,
                                                                  Strings.NoTypeConverterForRestore0,
                                                                  typeOfT.Name));
            }
            catch (Exception ex)
            {
                string message = string.Format(Strings.Culture, Strings.FailedToConvert0T1, value, typeOfT.Name);
                throw new Exception(message, ex);
            }
        }