How can I get all constants of a type by reflection?

C#.NetReflectionConstants

C# Problem Overview


How can I get all constants of any type using reflection?

C# Solutions


Solution 1 - C#

Though it's an old code:

private FieldInfo[] GetConstants(System.Type type)
{
    ArrayList constants = new ArrayList();

    FieldInfo[] fieldInfos = type.GetFields(
        // Gets all public and static fields

        BindingFlags.Public | BindingFlags.Static | 
        // This tells it to get the fields from all base types as well

        BindingFlags.FlattenHierarchy);
    
    // Go through the list and only pick out the constants
    foreach(FieldInfo fi in fieldInfos)
        // IsLiteral determines if its value is written at 
        //   compile time and not changeable
        // IsInitOnly determines if the field can be set 
        //   in the body of the constructor
        // for C# a field which is readonly keyword would have both true 
        //   but a const field would have only IsLiteral equal to true
        if(fi.IsLiteral && !fi.IsInitOnly)
            constants.Add(fi);           

    // Return an array of FieldInfos
    return (FieldInfo[])constants.ToArray(typeof(FieldInfo));
}

Source

You can easily convert it to cleaner code using generics and LINQ:

private List<FieldInfo> GetConstants(Type type)
{
    FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public |
         BindingFlags.Static | BindingFlags.FlattenHierarchy);
    
    return fieldInfos.Where(fi => fi.IsLiteral && !fi.IsInitOnly).ToList();
}

Or with one line:

type.GetFields(BindingFlags.Public | BindingFlags.Static |
               BindingFlags.FlattenHierarchy)
    .Where(fi => fi.IsLiteral && !fi.IsInitOnly).ToList();

Solution 2 - C#

If you would like to get the values of all constants of a specific type, from the target type, here is an extension method (extending some of the answers on this page):

public static class TypeUtilities
{
    public static List<T> GetAllPublicConstantValues<T>(this Type type)
    {
        return type
            .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
            .Where(fi => fi.IsLiteral && !fi.IsInitOnly && fi.FieldType == typeof(T))
            .Select(x => (T)x.GetRawConstantValue())
            .ToList();
    }
}

Then for a class like this

static class MyFruitKeys
{
    public const string Apple = "apple";
    public const string Plum = "plum";
    public const string Peach = "peach";
    public const int WillNotBeIncluded = -1;
}

You can obtain the string constant values like this:

List<string> result = typeof(MyFruitKeys).GetAllPublicConstantValues<string>();
//result[0] == "apple"
//result[1] == "plum"
//result[2] == "peach"

Solution 3 - C#

As Type extensions:

public static class TypeExtensions
{
	public static IEnumerable<FieldInfo> GetConstants(this Type type)
	{
		var fieldInfos = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);

		return fieldInfos.Where(fi => fi.IsLiteral && !fi.IsInitOnly);
	}

	public static IEnumerable<T> GetConstantsValues<T>(this Type type) where T : class
	{
		var fieldInfos = GetConstants(type);

		return fieldInfos.Select(fi => fi.GetRawConstantValue() as T);
	}
}

Solution 4 - C#

Use property.GetConstantValue() to get value.

Solution 5 - C#

public class Constants
{
    public class InputType
    {
        public const string DOCUMENTPHOTO = "document-photo";
        public const string SELFIEPHOTO = "selfie-photo";
        public const string SELFIEVIDEO = "selfie-video";
        public static List<string> Domain { get { return typeof(Constants.InputType).GetAllPublicConstantValues<string>(); } }
    }
    public class Type
    {
        public const string DRIVINGLICENSE = "driving-license";
        public const string NATIONALID = "national-id";
        public const string PASSPORT = "passport";
        public const string PROOFOFRESIDENCY = "proof-of-residency";
        public static List<string> Domain { get { return typeof(Constants.Type).GetAllPublicConstantValues<string>(); } }
    }
    public class Page
    {
        public const string FRONT = "front";
        public const string BLACK = "back";
        public static List<string> Domain { get { return typeof(Constants.Page).GetAllPublicConstantValues<string>(); } }
    }
    public class FileType
    {
        public const string FRONT = "selfie";
        public const string BLACK = "video";
        public const string DOCUMENT = "document";
        public const string MEDIA = "media";
        public const string CAPTCHA = "captcha";
        public const string DIGITALSIGNATURE = "digitalSignature";
        public static List<string> Domain { get { return typeof(Constants.FileType).GetAllPublicConstantValues<string>(); } }
    }
}

public static class TypeUtilities
{
    public static List<T> GetAllPublicConstantValues<T>(this Type type)
    {
        return type
            .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
            .Where(fi => fi.IsLiteral && !fi.IsInitOnly && fi.FieldType == typeof(T))
            .Select(x => (T)x.GetRawConstantValue())
            .ToList();
    }
}

Use: var inputTypeDomain = Constants.InputType.Domain;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmasoud ramezaniView Question on Stackoverflow
Solution 1 - C#gdoron is supporting MonicaView Answer on Stackoverflow
Solution 2 - C#BCAView Answer on Stackoverflow
Solution 3 - C#bytedevView Answer on Stackoverflow
Solution 4 - C#Reza BayatView Answer on Stackoverflow
Solution 5 - C#Wendell CarvalhoView Answer on Stackoverflow