This has been one of several nagging curiosities in the back of my mind for quite some time, but until recently, I never had much motivation to explore the question…
Recently, I was given the assignment to deploy some .NET code that would activate an auditing feature with a variety of enumerated flags. I wanted to make sure I provided enough flexibility in my component such that any combination of the flags could be set from outside the component without the need to recompile the component—the easy answer was to provide a means to set these flags from configuration.
I know I’ve seen other components do this—particularly different logging components—so there ought to be an easy way to set an enumeration from XML, but what is it? Well, here’s the short-and-dirty solution:
Imagine this kind of configuration file:
<configuration>
<appSettings>
<add key="MyEnumSettings" value="OptionOne,OptionTwo"/>
</appSettings>
</configuration>
Here’s code you can use to parse and convert string representations of an enumerator into the actual enumerator type:
public enum SomeEnumFlag
{
None,
OptionOne,
OptionTwo,
OptionThree,
MoreOptions
}
class Program
{
static void Main(string[] args)
{
string enumSettings = ConfigurationManager.AppSettings["MyEnumSettings"];
string[] settingsArray = enumSettings.Split(new[] { ',' });
SomeEnumFlag myEnumSettings = new SomeEnumFlag();
foreach (string setting in settingsArray)
{
try
{
SomeEnumFlag settingFromConfig =
(SomeEnumFlag)Enum.Parse(typeof(SomeEnumFlag), setting.Trim(), true);
//use the bitwise operator to concatenate enum values together
myEnumSettings |= settingFromConfig;
}
catch (ArgumentException ex)
{
//if my config feeds a bad enum value, ArgumentException will be thrown
}
}
if (myEnumSettings == SomeEnumFlag.None)
{
//my enum defaults to None and will remain so if no values were
//found in the config
}
}
}
Side note: my real-life problem dealt with a SharePoint enumerator, but, since I have yet to set up a SharePoint development environment at home, I decided to create my own enumerator for this example. The concept is still the same, though.