-6
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()?

skm
  • 5,015
  • 8
  • 43
  • 104
  • 1
    Are you asking how to add values to a `List<>`? How to dynamically get properties from any given class with reflection? Something else? – David Jan 26 '23 at 17:35
  • 1
    This *can* be done, but is there any reason you're not storing these values in a `Dictionary` to begin with? (As an aside, I'd imagine you either want these values to be `const` or to make them properties, because it stands they're global variables that anyone can tweak at will, which is very bad for maintainability.) – Jeroen Mostert Jan 26 '23 at 17:40

1 Answers1

-1

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;
    }
}
Kurubaran
  • 8,696
  • 5
  • 43
  • 65