2

I have a class in C#:

public static class Constants
{
    public static class Animals
    {
        public const string theDog = "dog";
        public const string theCat = "cat";
    }
}

And I want to loop through the "assignments" of that class (not the properties). And I want to get the values without having to explicitly specify the property. I'm trying to do this because I have a class of a a lot of constants and I want to add them to a list.

So, my desired output / code would look something like this:

foreach (string animal in Constants.Animals)
{
       Console.WriteLine(animal)
}

Output:

dog
cat

I have tried reflection, but that only gives me the property.

  • 3
    Show your reflection code and perhaps someone can help you get the value you're wanting – p3tch Jul 19 '18 at 13:57
  • 1
    Check this: https://stackoverflow.com/questions/10261824/how-can-i-get-all-constants-of-a-type-by-reflection – Afonso Jul 19 '18 at 13:57
  • you have written a sample of for loop, but for that to work you will need a foreach loop. or u need to change the syntax to for loop – Fuzzybear Jul 19 '18 at 13:58

2 Answers2

1

See this Reflection:- GetValue will give you the value.

foreach (PropertyInfo propertyinfo in typeof(yourClass).GetProperties())
        {
           if(propertyinfo !=null){
            var valueOfField=propertyinfo.GetValue(yourobject);
            var fieldname = propertyinfo.Name;

            if (valueOfField!=null && fieldname != null)
            {
              string data=fieldname +"="+valueOfField
            }
          }
        }
Hitesh Anshani
  • 1,499
  • 9
  • 19
1

Try using Reflection:

  using System.Reflection;

  ...

  var animals = typeof(Constants.Animals)
    .GetFields(BindingFlags.Public | BindingFlags.Static)
    .Where(field => field.IsLiteral)
    .Where(field => field.FieldType == typeof(String))
    .Select(field => field.GetValue(null) as String);

  Console.Write(string.Join(Environment.NewLine, animals));

Outcome:

  dog
  cat

if you want a loop

  foreach (string animal in animals) {
    Console.WriteLine(animal); 
  }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215