skm
skm

Reputation: 5679

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

Upvotes: -6

Views: 342

Answers (1)

Kurubaran
Kurubaran

Reputation: 8892

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;
    }
}

Upvotes: -1

Related Questions