Search code examples
c#asp.net-mvctype-conversiontypeofdynamictype

C# string to necessary type conversion


I have following situation. Lets say i receive list of string values. I have to assign those values to specific type properties in Model. Model example:

    public int ID { get; set; }
    public DateTime? Date { get; set; }

There is no problem in type conversion as i get array of property types with System.reflection and use Convert.ChangeType(string value, type). However, i can't assignt Convert.ChangeType results to model properties because it returns object not my desired type of value. A short example of my problem:

string s1 = "1";
string s2= "11-JUN-2015";
PropertyInfo[] matDetailsProperties = Model.GetType().GetProperties();
List<Type> types = new List<Type>();
        foreach(var item in Model)
        {
            types.Add(item.PropertyType);
        }

Model.ID = Convert.ChangeType(s1, types[0]);
Model.Date = Convert.ChangeType(s2, types[1]);

This does not work as Convert.ChangeType returns object and i can't just use (dateTime)Convert.ChangeType(...), that's "dirty code" as i have model with 17 properties with different types. It would be perfect if i could use (Type[0])Convert.ChangeType(...) but it is not possible in C#


Solution

  • You could use reflection. How about something like this?

    var prop = Model.GetType().GetProperty("ID");
    var propValue = Convert.ChangeType(s1, types[0]);
    if (prop != null && prop.CanWrite)
    {
        prop.SetValue(Model, propValue, null);
    }