stumped221
stumped221

Reputation: 99

dynamically populate properties of a class

I have the following code which takes some values from my App.config and tries to use them to populate the properties of a class.

foreach (string ReferenceKey in Utilities.CSVToList(ConfigurationManager.AppSettings[source + ":Keys"]))
{
    if (ConfigurationManager.AppSettings[ReferenceKey] != null && Incoming_Values.ContainsKey(ConfigurationManager.AppSettings[ReferenceKey]))
    { 
        PropertyInfo info = MyCustomClass.GetType().GetProperty(ReferenceKey.Split(':')[1]);
        info.SetValue(MyCustomClass, Incoming_Values[ConfigurationManager.AppSettings[ReferenceKey]]);
    }
    else
    {
        return null;
    }
}

The problem I'm having is that obviously the KVP I get from the config file are all going to be of type string, but the properties of the class are strongly typed. I'm trying to "loosely couple" the values and the class, but I have an issue where the property is not a string (e.g.. it's a datetime or an int or even a class of my own).

Does anyone have any idea how I would handle such a thing? Should I build a tranlator class or something?

Upvotes: 0

Views: 664

Answers (2)

Michael Sander
Michael Sander

Reputation: 2737

Take a look at custom configuration sections, they provide you with strongly typed access to the app.config values. You can then loose couple this to your classes as you wish.

How to: Create Custom Configuration Sections Using ConfigurationSection (MSDN)

How to create custom config section in app.config (stack overflow)

Upvotes: 1

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

There are existing utilities in the framework that can help you with that.

One simple function is the Convert.ChangeType method, but it's not very customizable and is only limited to conversions between types that are part of what IConvertible can manage. If that's sufficient, go ahead.

Here's another approach that's more pluggable: you can use TypeConverters. You can get a TypeConverter from the TypeDescriptor class:

TypeDescriptor.GetConverter(targetType).ConvertFromInvariantString(configValue)

You can define custom TypeConverter classes if needed. This may or may not be better than implementing your own solution from scratch. It's up to you to decide depending on your needs.

Upvotes: 1

Related Questions