static class to Dictionary<string, string> in c#
-
26-10-2019 - |
Question
I have a static class which only contains string properties. I want to convert that class into a name-value pair dictionary with key=PropName
, value=PropValue
.
Below is the code I have written:
void Main()
{
Dictionary<string, string> items = new Dictionary<string, string>();
var type = typeof(Colors);
var properties = type.GetProperties(BindingFlags.Static);
/*Log properties found*/
/*Iam getting zero*/
Console.WriteLine("properties found: " +properties.Count());
foreach (var item in properties)
{
string name = item.Name;
string colorCode = item.GetValue(null, null).ToString();
items.Add(name, colorCode);
}
/*Log items created*/
Console.WriteLine("Items in dictionary: "+items.Count());
}
public static class Colors
{
public static string Gray1 = "#eeeeee";
public static string Blue = "#0000ff";
}
Output
properties found: 0
Items in dictionary: 0
It's not reading any properties - can anybody tell me what's wrong with my code?
Solution
The members in your Colors
class are no properties but fields.
Use GetFields
in the place of the GetProperties method.
You might end up with something like (also not the change in the call to GetValue
):
var properties = type.GetFields(BindingFlags.Static);
/*Log properties found*/
/*Iam getting zero*/
Console.WriteLine("properties found: " +properties.Count());
foreach (var item in properties)
{
string name = item.Name;
string colorCode = item.GetValue(null).ToString();
items.Add(name, colorCode);
}
OTHER TIPS
You can use linq to condense the conversion to a couple of lines:
var type = typeof(Colors);
var fields = type.GetFields().ToDictionary(f => f.Name, f => f.GetValue(f).ToString());
Use this:
var properties = type.GetFields(BindingFlags.Static|BindingFlags.Public);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow