views:

33

answers:

1

I want to make a static class that would load some settings from XML file and apply those settings to its own properties.

I am trying to use the following code but I don't really know what to give to the SetValue method since the class for which we want to set the property is static.

// some code removed ...
Type settingsType = typeof(Settings);   // Settings is a static class

foreach (PropertyInfo propertyInformation in settingsType.GetProperties(BindingFlags.Public |
                                  BindingFlags.Static))
{
        //------------------------------------------------------------
        //  Determine if configured setting matches current setting based on name
        //------------------------------------------------------------
        if (propertyInformation.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
        {
        //------------------------------------------------------------
        //  Attempt to apply configured setting
        //------------------------------------------------------------
        try
        {
        if (propertyInformation.CanWrite)
        {
        propertyInformation.SetValue(this, Convert.ChangeType(value, propertyInformation.PropertyType, CultureInfo.CurrentCulture), null);
        }
        }
        catch
        {
        }
            break;
        }

}

Is it even possible to set properties on static classes with reflection?

+5  A: 

Just pass null for the instance.

leppie
using "typeof(Settings)" in place of "this" works too
mare
@mare: Perhaps it gets ignored for static members.
leppie