C#: Using Reflection to get constant values

It is generally good design practice to put constants in a static class to centralise messages and by using constants we can find typo’s at compile time instead of using string literals everywhere.

A common naming standard is also used which helps with auto-complete in Visual Studio, and will help us here by filtering constants if required.

An example constants class may be:

public class Constants
{
  public const string VALIDATION_CONCURRENCY = "This project was been modified by another user, please reload and try again.";
  public const string VALIDATION_REQUIRED = "The field {0} is empty and must be completed.";

  public const string EMAIL_MESSAGE_STD = "Dear {0}, blahblah";
}

Now we may be required to compile a list of validation messages for, say, spell and grammatical review. We could copy and paste and remove the C# parts using regular expressions, this is one way. Another way is to use reflection to find all validation constants in the Constants class. Here is the code:

            List<string> messages = new List<string>();
            foreach (FieldInfo field in typeof(Constants).GetFields().Where(f => f.Name.StartsWith("VALIDATION_")))
            {
                    messages.Add(field.GetRawConstantValue().ToString());
            }

2 Responses to C#: Using Reflection to get constant values

  1. Thank you very much, this is exactly what I have been trying to do. I can now use the nicely named constant and still be able to output both the value and name of the constant when under test conditions (I have a static class with nested classes that contain the constants, so the constants are broken up logically).

    i.e. AccessRight.Files.CreateNewFile

    the final piece of the puzzle (actually getting the value of the constant from its FieldInfo) you have just solved for me 🙂

  2. harveydarvey says:

    Thanks for the short and concise explaination.

Leave a comment