Wellspring Wellspring - 1 year ago 78
ASP.NET (C#) Question

How to loop through a static class of constants?

Instead of using a Switch statement as shown in the code below, is there an alternative way to check if

is a match to any of the constants in the

The intended goal is to loop through all of the constant values to see if
is a match, rather than having to specify each constant as a

Parent Class:

public class Parent
public static class Child
public const string JOHN = "John";
public const string MARY = "Mary";
public const string JANE = "Jane";


switch (foo.Type)
case Parent.Child.JOHN:
case Parent.Child.MARY:
case Parent.Child.JANE:
// Do Something

Answer Source

You can find all constant values in the class:

var values = typeof(Parent.Child).GetFields(BindingFlags.Static | BindingFlags.Public)
                                 .Where(x => x.IsLiteral && !x.IsInitOnly)
                                 .Select(x => x.GetValue(null)).Cast<string>();

Then you can check if values contains something:

if(values.Contains("something")) {/**/}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download