Example #1
0
        /// <summary>
        /// Try and convert the value of a term to type T
        /// </summary>
        /// <typeparam name="T">Type to convert to</typeparam>
        /// <param name="row">A row object</param>
        /// <param name="term">The name of the term to convert</param>
        /// <param name="value">Value to return</param>
        /// <returns>A ConvertResult object that is true on success.  On failure will return false an contain an error message</returns>
        public static ConvertResult TryConvert <T>(this IRow row, string term, out T value)
        {
            if (!row.TryGetField(term, out string data))
            {
                value = default;
                return(ConvertResult.Failed($"Term {term} not found"));
            }
            var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));

            if (!converter.IsValid(data))
            {
                value = default;
                return(ConvertResult.Failed($"Term {term} with value {data ?? "(null)"} could not be converted to type {typeof(T)}"));
            }
            value = (T)converter.ConvertFrom(data);
            return(ConvertResult.Success);
        }
Example #2
0
        /// <summary>
        /// Try and convert the value of a term to type T
        /// </summary>
        /// <typeparam name="T">Type to convert to</typeparam>
        /// <param name="row">A row object</param>
        /// <param name="index">The index of the field to convert</param>
        /// <param name="value">Value to return</param>
        /// <returns>A ConvertResult object that is true on success.  On failure will return false an contain an error message</returns>
        public static ConvertResult TryConvert <T>(this IRow row, int index, out T value)
        {
            if (index < 0 || index >= row.FieldMetaData.Length)
            {
                value = default;
                return(ConvertResult.Failed($"Index {index} out of range"));
            }
            string data      = row[index];
            var    converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));

            if (!converter.IsValid(data))
            {
                value = default;
                return(ConvertResult.Failed($"Field at index {index} with value {data ?? "(null)"} could not be converted to type {typeof(T)}"));
            }
            value = (T)converter.ConvertFrom(data);
            return(ConvertResult.Success);
        }