ffyhlkain
ffyhlkain

Reputation: 57

set property type dynamically in c#

I got the following problem with my data stream:

The data stream consists of a dictionary, which I want to parse and specify the type of the value dynamically.

I.e. my data strea includes:

Now I would like to set my properties of a generic class according to this data stream:

class GenericClass
{
    Hashtable genericAttributes;
}

Is there a possibility to set my values of the data stream to the correct type via reflection?

I could try something like:

DateTime.TryParse(date, out myDate);

for the date time object, but I don't think this will work when trying to parse doubles, floats, int16s, int32s, uint16,...

Some thoughts on that?

Thx and regards

Upvotes: 3

Views: 2699

Answers (1)

flindeberg
flindeberg

Reputation: 5027

My guess from your question is that they all are IConvertible, so I would do something my code example below. The idea is that I specify the "want"-order, ie in the order I want the types if they can fit multiple types, and then I try to convert them in that order.

    public class GenericPropClass
    {
        public Type type;
        public object value;
        public string key;
    }

    [TestMethod]
    public void PropertySet()
    {
        var dict = new Dictionary<string, string>();
        var resultingList = new List<GenericPropClass>();
        // Specify the order with most "specific"/"wanted" type first and string last
        var order = new Type[] { typeof(DateTime), typeof(int), typeof(double), typeof(string) }; 

        foreach (var key in dict.Keys)
            foreach (var t in order)
            {
                try
                {
                    var res = new GenericPropClass()
                    {
                        value = Convert.ChangeType(dict[key], t),
                        key = key,
                        type = t,
                    };
                    resultingList.Add(res);
                    break;
                }
                catch (Exception)
                {
                    // Just continue
                }
            }

    }

Sorry for a short answer containing almost only code, I might have time to improve it tonight to get my thoughts in, but I have to go now :)

Upvotes: 2

Related Questions