279

I have a class that I want to use to store "properties" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add typed properties, so that the "value" returned is always of the type that I want it to be.

The type should always be a primitive. This class subclasses an abstract class which basically stores the name and value as string. The idea being that this subclass will add some type-safety to the base class (as well as saving me on some conversion).

So, I have created a class which is (roughly) this:

public class TypedProperty<DataType> : Property
{
    public DataType TypedValue
    {
        get { // Having problems here! }
        set { base.Value = value.ToString();}
    }
}

So the question is:

Is there a "generic" way to convert from string back to a primitive?

I can't seem to find any generic interface that links the conversion across the board (something like ITryParsable would have been ideal!).

3
  • I'd be interested in seeing an example of your concrete class, even just a snippet. :)
    – Jon Limjap
    Aug 12, 2008 at 9:54
  • can you please post the relevant parts of your base class?
    – JJS
    Jul 11, 2012 at 21:26
  • I wonder if anyone can get the answers here working in .Net Standard 1.2 :/
    – Dan Rayson
    Nov 3, 2018 at 15:21

11 Answers 11

444

I am not sure whether I understood your intentions correctly, but let's see if this one helps.

public class TypedProperty<T> : Property where T : IConvertible
{
    public T TypedValue
    {
        get { return (T)Convert.ChangeType(base.Value, typeof(T)); }
        set { base.Value = value.ToString();}
    }
}
4
  • I've been wondering for a few days how to deserialize a stream into a generic type. Thanks :)
    – Trap
    Sep 30, 2008 at 22:13
  • 3
    I agree, although Convert.ChangeType is not very universal and extensible solution, it works for most basic types. if something better is needed, it's no problem to wrap this method into something bigger like Tim suggested or use different conversion method altogether. Jan 11, 2010 at 15:11
  • 19
    I would definitely add the where T:IConvertible
    – MikeT
    Nov 7, 2013 at 10:45
  • 8
    Type T should not be IConvertible, but Type of base.Value should.
    – chapluck
    Sep 15, 2015 at 13:52
88

lubos hasko's method fails for nullables. The method below will work for nullables. I didn't come up with it, though. I found it via Google: http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx Credit to "Tuna Toksoz"

Usage first:

TConverter.ChangeType<T>(StringValue);  

The class is below.

public static class TConverter
{
    public static T ChangeType<T>(object value)
    {
        return (T)ChangeType(typeof(T), value);
    }

    public static object ChangeType(Type t, object value)
    {
        TypeConverter tc = TypeDescriptor.GetConverter(t);
        return tc.ConvertFrom(value);
    }

    public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
    {

        TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
    }
}
5
  • i would add a Fallback convert options for Enums and Other Complex structures, but good call.
    – Tomer W
    Mar 27, 2012 at 14:10
  • 2
    Why the RegisterTypeConverter? Do we need to register the converters before hand? (unfortunately the link is dead, so I couldn't read up on it)
    – Cohen
    Nov 30, 2012 at 9:40
  • For multiple conversions you should probably create tc (the TypeConverter) one time only. TypeConverter is slow because it uses reflection to search for the TypeConverterAttribute. If you initialize a single private TypeConverter field, then you should be able to re-use the TypeConverter many times. Jan 21, 2013 at 8:44
  • 1
    Works fine, but if T is an object, throws an exception. I was able to workaround that by using ` if (typeof(T).IsPrimitive) { return TConverter.ChangeType<T>(StringValue); } else { object o=(object)StringValue; return (T)o; }` as replacement for the Usage sample TConverter.ChangeType<T>(StringValue)
    – Matt
    Feb 24, 2016 at 17:26
  • if i do TConverter.ChangeType<T>(item.Key) and T is int and item.key is int then i recive exception Int32Converter cannot convert from System.Int32 - how to fix this ?
    – Dorian
    Oct 21, 2022 at 12:14
21

For many types (integer, double, DateTime etc), there is a static Parse method. You can invoke it using reflection:

MethodInfo m = typeof(T).GetMethod("Parse", new Type[] { typeof(string) } );

if (m != null)
{
    return m.Invoke(null, new object[] { base.Value });
}
12
TypeDescriptor.GetConverter(PropertyObject).ConvertFrom(Value)

TypeDescriptor is class having method GetConvertor which accept a Type object and then you can call ConvertFrom method to convert the value for that specified object.

1
  • I personally think this interface is better for handling convertion instead of the method Convert.ChangeType since you need to implement the IConvertible interface on all your class.
    – Sauleil
    Nov 29, 2019 at 4:01
9

With inspiration from the Bob's answer, these extensions also support null value conversion and all primitive conversion back and fourth.

public static class ConversionExtensions
{
        public static object Convert(this object value, Type t)
        {
            Type underlyingType = Nullable.GetUnderlyingType(t);

            if (underlyingType != null && value == null)
            {
                return null;
            }
            Type basetype = underlyingType == null ? t : underlyingType;
            return System.Convert.ChangeType(value, basetype);
        }

        public static T Convert<T>(this object value)
        {
            return (T)value.Convert(typeof(T));
        }
}

Examples

            string stringValue = null;
            int? intResult = stringValue.Convert<int?>();

            int? intValue = null;
            var strResult = intValue.Convert<string>();
4

You could possibly use a construct such as a traits class. In this way, you would have a parameterised helper class that knows how to convert a string to a value of its own type. Then your getter might look like this:

get { return StringConverter<DataType>.FromString(base.Value); }

Now, I must point out that my experience with parameterised types is limited to C++ and its templates, but I imagine there is some way to do the same sort of thing using C# generics.

1
4

Check the static Nullable.GetUnderlyingType. - If the underlying type is null, then the template parameter is not Nullable, and we can use that type directly - If the underlying type is not null, then use the underlying type in the conversion.

Seems to work for me:

public object Get( string _toparse, Type _t )
{
    // Test for Nullable<T> and return the base type instead:
    Type undertype = Nullable.GetUnderlyingType(_t);
    Type basetype = undertype == null ? _t : undertype;
    return Convert.ChangeType(_toparse, basetype);
}

public T Get<T>(string _key)
{
    return (T)Get(_key, typeof(T));
}

public void test()
{
    int x = Get<int>("14");
    int? nx = Get<Nullable<int>>("14");
}
1

I used lobos answer and it works. But I had a problem with the conversion of doubles because of the culture settings. So I added

return (T)Convert.ChangeType(base.Value, typeof(T), CultureInfo.InvariantCulture);
1

You can do it in one line as below:

YourClass obj = (YourClass)Convert.ChangeType(YourValue, typeof(YourClass));

Happy coding ;)

1
  • When you shared code as answer, please try to explain it. Mar 6, 2020 at 13:48
0
public class TypedProperty<T> : Property
{
    public T TypedValue
    {
        get { return (T)(object)base.Value; }
        set { base.Value = value.ToString();}
    }
}

I using converting via an object. It is a little bit simpler.

2
  • thanks I have to convert a T in a interface and the simple conversion T object works correctly, easy and fast thanks
    – LXG
    Feb 10, 2012 at 9:42
  • 6
    (int)(object)"54"; is a FATALITY!, this is not VB!
    – Tomer W
    Mar 27, 2012 at 14:08
0

Yet another variation. Handles Nullables, as well as situations where the string is null and T is not nullable.

public class TypedProperty<T> : Property where T : IConvertible
{
    public T TypedValue
    {
        get
        {
            if (base.Value == null) return default(T);
            var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
            return (T)Convert.ChangeType(base.Value, type);
        }
        set { base.Value = value.ToString(); }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.