Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dynamically Get Variable Names and Values in a Class

I am currently making a program (C# .Net 4) that has multiple options, which are saved to a file.

These options are their own variables in-code, and I was wondering if there was a way to get the variables and values of these options dynamically in code.

In my case, I have these options in a "Settings" class, and I access them from my main form class using Settings.varSetting.

I get and set these variables in multiple places in code; is it possible to consolidate the list of variables so that I can access and set them (for example, creating a Settings form which pulls the available options and their values and draws the form dynamically) more easily/consistently?

Here are the current variables I have in the Settings class:

    public static Uri uriHomePage = new Uri("http://www.google.com");
    public static int intInitOpacity = 100;
    public static string strWindowTitle = "OpaciBrowser";
    public static bool boolSaveHistory = false;
    public static bool boolAutoRemoveTask = true; //Automatically remove window from task bar if under:
    public static int intRemoveTaskLevel = 50; //percent
    public static bool boolHideOnMinimized = true;

Thanks for any help,

Karl Tatom ( TheMusiKid )

like image 546
TheMusiKid Avatar asked Mar 14 '26 03:03

TheMusiKid


2 Answers

You might want to consider using the Application Settings features built into the framework for loading and storing application settings.

like image 159
Reed Copsey Avatar answered Mar 16 '26 18:03

Reed Copsey


var dict = typeof(Settings)
    .GetFields(BindingFlags.Static | BindingFlags.Public)
    .ToDictionary(f=>f.Name, f=>f.GetValue(null));
like image 35
L.B Avatar answered Mar 16 '26 18:03

L.B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!