Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over properties in a static class

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.

like image 544
Sait Avatar asked Dec 15 '22 16:12

Sait


1 Answers

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)

like image 166
Marc Gravell Avatar answered Dec 29 '22 09:12

Marc Gravell