DooDoo
DooDoo

Reputation: 13487

How to get all static properties and its values of a class using reflection

I hava a class like this:

public class tbl050701_1391_Fields
{
    public static readonly string StateName = "State Name";
    public static readonly string StateCode = "State Code";
    public static readonly string AreaName = "Area Name";
    public static readonly string AreaCode = "Area Code";
    public static readonly string Dore = "Period";
    public static readonly string Year = "Year";
}

I want to write some statement that returns a Dictionary<string, string> that has these values:

Key                            Value
--------------------------------------------
"StateName"                    "State Name"
"StateCode"                    "State Code"
"AreaName"                     "Area Name"
"Dore"                         "Period"
"Year"                         "Year"

I have this code for getting one property value:

public static string GetValueUsingReflection(object obj, string propertyName)
{
    var field = obj.GetType().GetField(propertyName, BindingFlags.Public | BindingFlags.Static);
    var fieldValue = field != null ? (string)field.GetValue(null) : string.Empty;
    return fieldValue;
}

How I can get all properties and their values?

Upvotes: 54

Views: 35288

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503489

how I can get all properties and their values?

Well to start with, you need to distinguish between fields and properties. It looks like you've got fields here. So you'd want something like:

public static Dictionary<string, string> GetFieldValues(object obj)
{
    return obj.GetType()
              .GetFields(BindingFlags.Public | BindingFlags.Static)
              .Where(f => f.FieldType == typeof(string))
              .ToDictionary(f => f.Name,
                            f => (string) f.GetValue(null));
}

Note: null parameter is necessary for GetValue for this to work since the fields are static and don't belong to an instance of the class.

Upvotes: 114

Related Questions