user1071461
user1071461

Reputation:

Understanding enums

I'm trying to figure out how enums work, I'm trying to make a function to write to the registry, using an enum for the root of the registry, but kinda confused

public enum RegistryLocation
        {
            ClassesRoot = Registry.ClassesRoot,
            CurrentUser = Registry.CurrentUser,
            LocalMachine = Registry.LocalMachine,
            Users = Registry.Users,
            CurrentConfig = Registry.CurrentConfig
        }

public void RegistryWrite(RegistryLocation location, string path, string keyname, string value)
{
     // Here I want to do something like this, so it uses the value from the enum
     RegistryKey key;
     key = location.CreateSubKey(path);
     // so that it basically sets Registry.CurrentConfig for example, or am i doing it wrong
     ..
}

Upvotes: 2

Views: 293

Answers (1)

competent_tech
competent_tech

Reputation: 44921

The problem is that you are trying to initialize the enum values using classes and use enum values as classes, which you cannot do. From MSDN:

The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

What you could do is have the enum as a standard enum and then have a method return the correct RegistryKey based on the enum.

For example:

    public enum RegistryLocation
    {
        ClassesRoot,
        CurrentUser,
        LocalMachine,
        Users,
        CurrentConfig
    }

    public RegistryKey GetRegistryLocation(RegistryLocation location)
    {
        switch (location)
        {
            case RegistryLocation.ClassesRoot:
                return Registry.ClassesRoot;

            case RegistryLocation.CurrentUser:
                return Registry.CurrentUser;

            case RegistryLocation.LocalMachine:
                return Registry.LocalMachine;

            case RegistryLocation.Users:
                return Registry.Users;

            case RegistryLocation.CurrentConfig:
                return Registry.CurrentConfig;

            default:
                return null;

        }
    }

    public void RegistryWrite(RegistryLocation location, string path, string keyname, string value) {
         RegistryKey key;
         key = GetRegistryLocation(location).CreateSubKey(path);
    }

Upvotes: 4

Related Questions