I'm trying to load some AppSettings into an object. The settings look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Logging_default_path" value="C:\Temp" />
<add key="Logging_max_file_size" value="10485760" />
<add key="Logging_levels" value="Error,Warning,Info"/>
<add key="Logging_filename" value="RobinsonLog" />
</appSettings>
</configuration>
The Logging_levels represents several enum values that are allowed by the settings. I'm trying to load these into my object by using the following code:
Level = (LogLevel)Enum.Parse(typeof(LogLevel), settings["Logging_levels"]);
But this is not working and I'm only getting LogLevel.Info returned, not the value of Loglevel.Error | LogLevel.Warning | LogLevel.Info. The enum is defined as followed:
[Flags]
public enum LogLevel
{
Error = 0x0,
Warning = 0x1,
Info = 0x2,
Debug = 0x3,
Performance = 0x4
}
Am I wrong by defining the values in hex? or did I miss something else?
The problem isn't the parsing! The problem is the conversion to text, instead. Because the flag values aren't distinct bit masks, there is no deterministic mapping to string and back. As mentioned by others, you should choose the values like e.g.:
See MSDN: Parsing Enumeration Values
See a demo live: https://ideone.com/8AkSQ
Output:
Performance Note:
If performance is important, do not rely on Enum.Parse :)
See How should I convert a string to an enum in C#?
So it should work, and ik looks like it does:
Gives me "Error" and "Warning". However, by inspecting the
level
variable in Visual Studio, it only shows "Warning". Perhaps that set you off. ;-)Edit: @svick and @jv42 are right, it are your flag values that are wrong.
Proper flag values might help (each value should set a different bit):
Note: you can remove the 'None' if you wish.
Your
enum
values are going to cause problems.The values of a
Flags
enum
must be powers of two, and you shouldn't use 0 for any value other than some kind of empty/none/nothing indicator.Does this make any difference?