9

Instead of using a Switch statement as shown in the code below, is there an alternative way to check if foo.Type is a match to any of the constants in the Parent.Child class?

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

Parent Class:

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

Code:

switch (foo.Type)
{
     case Parent.Child.JOHN:
     case Parent.Child.MARY:
     case Parent.Child.JANE:
         // Do Something
         break;
}
Daniel Congrove
  • 3,519
  • 2
  • 35
  • 59
  • can you define all the constants in an array, and loop through that array to check constant values? – Peter Nov 12 '16 at 01:43
  • You can put all the constant values in an ArrayList, iterate over the list while comparing if a particular element is equal to foo.Type. – HaroldSer Nov 12 '16 at 01:45
  • this might help http://stackoverflow.com/questions/14971631/convert-an-enum-to-liststring, then just do an **IndexOf(foo.Type)** – Jeremy Thompson Nov 12 '16 at 01:48

3 Answers3

9

Using Reflection 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")) {/**/}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
1

While you can loop through constants that are declared like that using reflection (as the other answers show), it's not ideal.

It would be much more efficient to store them in some kind of enumerable object: an array, List, ArrayList, whatever fits your requirements best.

Something like:

public class Parent {
    public static List<string> Children = new List<string> {"John", "Mary", "Jane"}
}

Then:

if (Parent.Children.Contains(foo.Type) {
    //do something
}
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
0

You can use reflection to get all constants of given class:

var type = typeof(Parent.Child);
FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public |
BindingFlags.Static | BindingFlags.FlattenHierarchy);

var constants = fieldInfos.Where(f => f.IsLiteral && !f.IsInitOnly).ToList();
var constValue = Console.ReadLine();
var match = constants.FirstOrDefault(c => (string)c.GetRawConstantValue().ToString() == constValue.ToString());
αNerd
  • 528
  • 1
  • 6
  • 11