Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to populate a List<string> with class constant values. C#

I'm in need to create a method which allows me to populate a List<string> with the values of the constants that are defined in the own class.

To give you a quick example of the numerous (20 in total) constants that are defined in the class:

private const string NAME1 = "NAME1";
private const string NAME2 = "NAME2";
private const string NAME3 = "NAME3";
...

As you can see, the name of the constant equals the value of it, if that can help.

So far, looking at examples of different types of solutions that I've found in StackOverflow about similar problems, I've come up with this:

public static List<string> GetConstantNames()
{
   List<string> names = new List<string>();
   Type type = typeof(ClassName);

   foreach (PropertyInfo property in type.GetType().GetProperties())
   {
      names.Add(property.Name);
   }

   return names;
}

My experience as a programmer is quite low, same as my experience with C#; I'm not sure if type.GetType().GetProperties() references the constant names, same happens with the property.Name line.

Does this method do what I'm asking?

like image 958
Jrene Avatar asked Jan 22 '20 11:01

Jrene


1 Answers

In order to get consts you should operate with fields, not properties:

  using System.Linq;
  using System.Reflection;

  ...

  public static List<string> GetConstantNames() {
    return typeof(ClassName)
      .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
      .Where(fi => fi.IsLiteral && !fi.IsInitOnly) // constants, not readonly
      .Where(fi => fi.FieldType == typeof(string)) // of type string
      .Select(fi => fi.Name) 
      .ToList();
  } 

If you want to get both const names and values:

  public static Dictionary<string, string> GetConstantNamesAndValues() {
    return typeof(ClassName)
      .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
      .Where(fi => fi.IsLiteral && !fi.IsInitOnly) // constants, not readonly
      .Where(fi => fi.FieldType == typeof(string)) // of type string
      .ToDictionary(fi => fi.Name, fi => fi.GetValue(null) as String); 
  } 
like image 70
Dmitry Bychenko Avatar answered Oct 10 '22 02:10

Dmitry Bychenko