5

I have a static class which stores some parameters about my program, like the following,

public static class Parameters
{
    public static string Path = "C:\\path.txt";
    public static double Sigma = 0.001;
    public static int Inputs = 300;
}

I would like to have a function which gives all the names and values of this class as a string value, something like:

public static string LogParameters()
{
     return "Path = C:\\path.txt" + Envrironment.NewLine + 
            "Sigma = 0.001" + Environment.NewLine + 
            "Inputs = 300";
}

I tried this similar SO question, How to loop through all the properties of a class?, however in this example they used a non-static class which they can refer as an object. So, I am unable to use their code.

Community
  • 1
  • 1
Sait
  • 19,045
  • 18
  • 72
  • 99

1 Answers1

13

Those aren't properties - they are fields:

foreach(FieldInfo field in typeof(Parameters).GetFields()) {
    Console.WriteLine("{0}={1}", field.Name, field.GetValue(null));
}

(obviously, adjust the above to write to a StringBuilder instead of to the Console)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900