Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Type, where Type is a variable

Tags:

c#

generics

I am attempting to create a standard method to handle populating a view model based on stored values in a cookie, that are used as user defaults for search criteria.

I am having issues when it comes to converting the string cookie values to the property type so the view model can be updated appropriately. Getting the following error:

Invalid cast from 'System.String' to 'System.Reflection.RuntimePropertyInfo'.

Here is what I have:

public TViewModel GetUserSearchCriteriaDefaults<TViewModel>(TViewModel viewModel)
        where TViewModel : class
{
    Type type = viewModel.GetType();
    string className = viewModel.GetType().Name;
    PropertyInfo[] properties = type.GetProperties();

    if (Request.Cookies[className] != null)
    {
        string rawValue;

        foreach (PropertyInfo property in properties)
        {
            if (!String.IsNullOrEmpty(Request.Cookies[className][property.Name]))
            {
                rawValue = Server.HtmlEncode(Request.Cookies[className][property.Name]);
                Type propertyType = property.GetType();
                var convertedValue = Convert.ChangeType(rawValue, propertyType); <---- Error from this line
                property.SetValue(viewModel, convertedValue);
            }
        }
    }

    return viewModel;
}
like image 683
crichavin Avatar asked Jul 17 '13 15:07

crichavin


1 Answers

change

Type propertyType = property.GetType();

to

Type propertyType = property.PropertyType;

Using GetType(), you get the type of property. And property is an instance of PropertyInfo.

like image 148
Raphaël Althaus Avatar answered Sep 30 '22 11:09

Raphaël Althaus