TheMusiKid
TheMusiKid

Reputation: 33

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 )

Upvotes: 3

Views: 6157

Answers (3)

L.B
L.B

Reputation: 116118

var dict = typeof(Settings)
    .GetFields(BindingFlags.Static | BindingFlags.Public)
    .ToDictionary(f=>f.Name, f=>f.GetValue(null));

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564413

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

Upvotes: 5

Related Questions