Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Strings to Type Instances

have you any alternative to these code, i want a more generic code I tried Convert class but with no success

        public object convert(Type type, string value)
        {
            object r = null;
            if (type == typeof(bool))
            {
                r = bool.Parse(value);
            }            
            else if (type == typeof(int))
            {
                r = int.Parse(value);
            }
            else if (type == typeof(string))
            {
                r = value;
            }

            return r; 
        }
like image 452
Said Avatar asked Mar 06 '26 01:03

Said


2 Answers

var conv = TypeDescriptor.GetConverter(type);
return conv.ConvertFromInvariantString(value);

Other conversion operations exist if you don't want "invariant". It depends on your needs. See also ConvertFromString if you want locale settins to apply, etc.

like image 85
Marc Gravell Avatar answered Mar 09 '26 10:03

Marc Gravell


You mention you have tried the Convert class, but have you also tried Convert.ChangeType(value, type)? What where the problems you ran in to?

like image 41
C.Evenhuis Avatar answered Mar 09 '26 10:03

C.Evenhuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!