Skip to main content

Retrieves a collection of constant names for a specified type in C# using reflection.

using System;
using System.Reflection;
using System.Linq;
using System.Collections.Generic;

internal class Program
{
    private class MyClass
    {
        private MyClass() { }

        static MyClass()
        {
            Instance = new MyClass();
        }

        public static MyClass Instance { get; private set; }

        public const string NameConst1 = "NameConst1";
        public const string NameConst2 = "NameConst2";
        public const string NameConst3 = "NameConst3";
    }

    public static IEnumerable<string> GetConstantNamesForType(Type objectType)
    {
        return
            from fieldInfo in objectType.GetFields()
            where (fieldInfo.Attributes & FieldAttributes.Literal) != 0
            select fieldInfo.Name;
    }

    private static void Main(string[] args)
    {
        foreach (var result in GetConstantNamesForType(MyClass.Instance.GetType()))
        {
            Console.WriteLine(result);
        }

        // >> NameConst1
        // >> NameConst2
        // >> NameConst3
    }
}