Search code examples
c#reflectionpropertydescriptor

Create a property and its type dynamically using propertydescriptor


I have a class that will has 2 properties

public class PropertyBag
{
    public string PropertyName {get;set;}
    public object PropertyValue {get;set;}
}

so this "PropertyValue" property can hold any primitive datatype i.e. int, datetime, string, etc.

I am reading settings from custom configuration file with nested elements. Something like this:

<Workspace name="ws1">
  <property name="version" type="decimal"> 1.3 </property>
  <property name="datetime" type="datetime"> 10-10-2015 </property>
  <property name="mainwindowlocation" type="string"> 10 300 850 </property>
  ...more nested elements...
</Workspace>  

I want to be able to set the type of the "PropertyValue" property dynamically based on the value from the config file. A colleague mentioned about PropertyDescriptors/TypeDescriptors/dynamic. Any suggestions with specific implementation detail ?

Thanks


Solution

  • You could simply use a switch statement to parse value based on the type value.

    var properties = XDocument.Load("XMLFile2.xml").Descendants("property").Select(p =>
    {
        string name = p.Attribute("name").Value;
        string type = p.Attribute("type").Value;
        string value = p.Value;
    
        PropertyBag bag = new PropertyBag();
        bag.PropertyName = name;
    
        switch (type)
        {
            case "decimal":
                bag.PropertyValue = Decimal.Parse(value);
                break;
    
            case "datetime":
                bag.PropertyValue = DateTime.Parse(value);
                break;
    
            default:
                bag.PropertyValue = value;
                break;
        }
    
        return bag;
    });