Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting properties with reflection on static classes

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?

like image 591
mare Avatar asked Aug 11 '10 16:08

mare


People also ask

Can a static class have properties C#?

A static class can only have static members — you cannot declare instance members (methods, variables, properties, etc.)

What is reflection in C# and how do you implement reflection?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

Can static class be inherited?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor.

What is the scope of static class specific?

The scope of a static class is limited to the application domain. Each app domain will have its own copy of any static variables you might have. If your "processes" are threads within the same app domain, then they will share the static values.


1 Answers

Just pass null for the instance.

like image 199
leppie Avatar answered Sep 23 '22 15:09

leppie