Converts this string into the specified type. - CSharp System

CSharp examples for System:String Convert

Description

Converts this string into the specified type.

Demo Code

//  Copyright ? 2011, Grid Protection Alliance.  All Rights Reserved.
using System.Text.RegularExpressions;
using System.Text;
using System.IO;/*from  w  w w  . j a v a2  s .  c om*/
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System;

public class Main{
        /// <summary>
        /// Converts this string into the specified type.
        /// </summary>
        /// <typeparam name="T"><see cref="Type"/> to convert string to.</typeparam>
        /// <param name="value">Source string to convert to type.</param>
        /// <param name="type"><see cref="Type"/> to convert string to.</param>
        /// <param name="culture"><see cref="CultureInfo"/> to use for the conversion.</param>
        /// <returns><see cref="String"/> converted to specfied <see cref="Type"/>; default value of specified type T if conversion fails.</returns>
        /// <remarks>
        /// This function makes use of a <see cref="TypeConverter"/> to convert this <see cref="String"/> to the specified <paramref name="type"/>,
        /// the best way to make sure <paramref name="value"/> can be converted back to its original type is to use the same
        /// <see cref="TypeConverter"/> to convert the original object to a <see cref="String"/>; see the
        /// <see cref="Common.TypeConvertToString(object)"/> method for an easy way to do this.
        /// </remarks>
        public static T ConvertToType<T>(this string value, Type type, CultureInfo culture)
        {
            // Don't proceed further if string is empty.
            if (string.IsNullOrEmpty(value))
                return default(T);

            // Initialize return type if not specified.
            if ((object)type == null)
                type = typeof(T);

            // Initialize culture info if not specified.
            if ((object)culture == null)
                culture = CultureInfo.InvariantCulture;

            try
            {
                if (type.IsAssignableFrom(typeof(bool)))
                {
                    // Handle booleans as a special case to allow numeric entries as well as true/false
                    return (T)((object)value.ParseBoolean());
                }
                else
                {
                    if (type.IsAssignableFrom(typeof(IConvertible)))
                    {
                        // This is faster for native types than using type converter...
                        return (T)Convert.ChangeType(value, type, culture);
                    }
                    else
                    {
                        // Handle objects that have type converters (e.g., Enum, Color, Point, etc.)
                        TypeConverter converter = TypeDescriptor.GetConverter(type);
                        return (T)converter.ConvertFromString(null, culture, value);
                    }
                }
            }
            catch
            {
                return default(T);
            }
        }
        /// <summary>
        /// Converts this string into the specified type.
        /// </summary>
        /// <typeparam name="T"><see cref="Type"/> to convert string to.</typeparam>
        /// <param name="value">Source string to convert to type.</param>
        /// <param name="type"><see cref="Type"/> to convert string to.</param>
        /// <returns><see cref="String"/> converted to specfied <see cref="Type"/>; default value of specified type T if conversion fails.</returns>
        /// <remarks>
        /// This function makes use of a <see cref="TypeConverter"/> to convert this <see cref="String"/> to the specified <paramref name="type"/>,
        /// the best way to make sure <paramref name="value"/> can be converted back to its original type is to use the same
        /// <see cref="TypeConverter"/> to convert the original object to a <see cref="String"/>; see the
        /// <see cref="Common.TypeConvertToString(object)"/> method for an easy way to do this.
        /// </remarks>
        public static T ConvertToType<T>(this string value, Type type)
        {
            return ConvertToType<T>(value, type, null);
        }
        /// <summary>
        /// Converts this string into the specified type.
        /// </summary>
        /// <typeparam name="T"><see cref="Type"/> to convert string to.</typeparam>
        /// <param name="value">Source string to convert to type.</param>
        /// <returns><see cref="String"/> converted to specfied <see cref="Type"/>; default value of specified type T if conversion fails.</returns>
        /// <remarks>
        /// This function makes use of a <see cref="TypeConverter"/> to convert this <see cref="String"/> to the specified type T,
        /// the best way to make sure <paramref name="value"/> can be converted back to its original type is to use the same
        /// <see cref="TypeConverter"/> to convert the original object to a <see cref="String"/>; see the
        /// <see cref="Common.TypeConvertToString(object)"/> method for an easy way to do this.
        /// </remarks>
        public static T ConvertToType<T>(this string value)
        {
            return ConvertToType<T>(value, null);
        }
        /// <summary>
        /// Parses a string intended to represent a boolean value.
        /// </summary>
        /// <param name="value">String representing a boolean value.</param>
        /// <returns>Parsed boolean value.</returns>
        /// <remarks>
        /// This function, unlike Boolean.Parse, correctly parses a boolean value, even if the string value
        /// specified is a number (e.g., 0 or -1). Boolean.Parse expects a string to be represented as
        /// "True" or "False" (i.e., Boolean.TrueString or Boolean.FalseString respectively).
        /// </remarks>
        public static bool ParseBoolean(this string value)
        {
            if (string.IsNullOrEmpty(value))
                return false;

            value = value.Trim();

            if (value.Length > 0)
            {
                // Try to parse string a number
                int iresult;

                if (int.TryParse(value, out iresult))
                {
                    return (iresult != 0);
                }
                else
                {
                    // Try to parse string as a boolean
                    bool bresult;

                    if (bool.TryParse(value, out bresult))
                    {
                        return bresult;
                    }
                    else
                    {
                        char test = value.ToUpper()[0];
                        return (test == 'T' || test == 'Y' ? true : false);
                    }
                }
            }

            return false;
        }
}

Related Tutorials