-2

I have a C# program that in the config file the user can specify Windows sounds to be played as a part of their routine. I have the sound in a variable "parameter" and it will have like "asterisk", "hand", "question", etc. In Java when I make Minecraft plugins, the enums have a .valueOf which I can pass a string and if that string matches one of the enum names, it returns it. I did System.Media.SystemSounds. and looked at what came up. There is no similar function (which I guess is expected, as it's not an enum I assume).

Is there a way to easily convert my string name into the matching SystemSound? I mean, I can switch on the string.ToLower() and make it that way but I'm hoping there is a one liner way.

Thanks!

Doug Matthews
  • 41
  • 1
  • 8

4 Answers4

0

is there a way to easily convert my string name into the matching SystemSound

Use a Dictionary<string, SystemSounds> and insert all your strings and sounds into this. Then later lookup the sound by the string key.

Otherwise, the term you are looking for is called reflection - Get property value from string using reflection in C#

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

If you start with an enum like this:

public enum Foo
{
    Bar = 42, Qaz = 99
}

Then you can do this:

Dictionary<string, Foo> map =
    typeof(Foo)
        .GetEnumValues()
        .Cast<Foo>()
        .Zip(
            typeof(Foo)
                .GetEnumValues()
                .Cast<int>(),
            (n, v) => new { n, v })
        .ToDictionary(x => x.n.ToString(), x => (Foo)x.v);

Console.WriteLine((int)map["Bar"]);
Console.WriteLine((int)map["Qaz"]);

That outputs:

42
99
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0

You could use reflection.

enum MyEnum {
  Asterix, Hand, Question
}

public static void Main(string[] args)
{
  var field = typeof(MyEnum).GetField("Asterix");

  var myEnum = field.GetValue(field);

}

the myEnum variable takes value of MyEnum.Asterix, based on a string variable supplied to the typeof(MyEnum).GetField("Asterix") method.

XomRng
  • 171
  • 12
0

If you need to access static properties of class SystemSounds by name, you can use reflection, as follows:

var sound = System.Media.SystemSounds.Asterisk;
Console.WriteLine(sound);
var name = "Asterisk";
var soundByName = typeof(System.Media.SystemSounds).GetProperty(name).GetValue(null, null); // null, null because it's a static property
Console.WriteLine(soundByName);
Console.WriteLine(sound == soundByName); // Should output 'true'
Pietro Martinelli
  • 1,776
  • 14
  • 16