mercredi 22 janvier 2020

Method to populate a List

I'm in need to create a method which allows me to populate a List 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?





Aucun commentaire:

Enregistrer un commentaire