Search code examples
c#static-classes

Function in a static C# class that can return the values of all of its public member variables


internal static class Items
{
    public static string ItemOne => "test";
    public static string ItemTwo => "test two";
    public static string ItemThree => "test three";        

    public static List<string> GetItemsValuesList()
    {

        // some code that can gather the values of all the member variables


        return new List<string>();
    }
}

I have already seen some other questions on SO but in my case, I am having a Static class. How can I return a list containing all the values of all the member variables by the method GetItemsValuesList()?


Solution

  • Try this,

    using System;
    using System.Collections.Generic;
    using System.Reflection;
    
    public static class MyStaticClass
    {
        public static int MyInt = 1;
        public static string MyString = "hello";
        public static bool MyBool = true;
    }
    
    public static class MyStaticHelper
    {
        public static List<object> GetAllValues()
        {
            List<object> values = new List<object>();
            Type type = typeof(MyStaticClass);
            FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);
            foreach (FieldInfo field in fields)
            {
                values.Add(field.GetValue(null));
            }
            return values;
        }
    }