Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Iterating through the enum return duplicate keys?

Tags:

c#

enums

registry

I am working now on some stuff regarding registry.

I checked the enum RegistryRights in System.Security.AccessControl.

public enum RegistryRights
{
    QueryValues = 1,
    SetValue = 2,
    CreateSubKey = 4,
    EnumerateSubKeys = 8,
    Notify = 16,
    CreateLink = 32,
    Delete = 65536,
    ReadPermissions = 131072,
    WriteKey = 131078,
    ExecuteKey = 131097,
    ReadKey = 131097,
    ChangePermissions = 262144,
    TakeOwnership = 524288,
    FullControl = 983103,
}

This enum is a bitwise,And I know that enums can contains duplicate values. I was trying to iterate through the enum by this code:

 foreach (System.Security.AccessControl.RegistryRights regItem in Enum.GetValues(typeof(System.Security.AccessControl.RegistryRights)))
        {
            System.Diagnostics.Debug.WriteLine(regItem.ToString() + "  " + ((int)regItem).ToString());
        }

also Enum.GetName(typeof(RegistryRights),regItem) return the same key name.

and the output I got is:


QueryValues  1
SetValue  2
CreateSubKey  4
EnumerateSubKeys  8
Notify  16
CreateLink  32
Delete  65536
ReadPermissions  131072
WriteKey  131078
ReadKey  131097
ReadKey  131097
ChangePermissions  262144
TakeOwnership  524288
FullControl  983103

Can someone please tell me why do I get duplicate keys?("ReadKey" instead of "ExecuteKey") How can I force it to cast the int to the second key of the value ? and why ToString does not return the real key value?

like image 485
RcMan Avatar asked Sep 01 '13 12:09

RcMan


1 Answers

I think you would have to iterate over the enum Names rather than values. Something like:

foreach (string regItem in Enum.GetNames(typeof(RegistryRights)))
{
    var value = Enum.Parse(typeof(RegistryRights), regItem);

    System.Diagnostics.Debug.WriteLine(regItem + "  " + ((int)value).ToString());
}

As to why this happens, there's no way for the runtime to know which name to return if the values are duplicate. This is why iterating through the names (which are guaranteed to be unique) produces the results you're looking for.

like image 59
M.Babcock Avatar answered Nov 14 '22 22:11

M.Babcock